简化开发,内置robbin实现负载均衡,熔断(需要三步手动配,添加配置文件,在接口上用一个类去写fallback)等机制,使得远程调用其他服务就像调用自己的服务一样便利
启动类上@EnableFeignClients 创建接口:
package com.example.consumeservice.client; import com.example.consumeservice.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; //底层实现负载均衡 @FeignClient("USER-SERVER")//服务名 public interface Userclient { @RequestMapping("/hello/{id}")//请求 User querybyid(@PathVariable("id") int id);//返回值 } // An highlighted block var foo = 'bar';控制器调用接口:
package com.example.consumeservice.Controller; import com.example.consumeservice.client.Userclient; import com.example.consumeservice.pojo.User; import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.ribbon.proxy.annotation.Hystrix; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; @Controller @DefaultProperties(defaultFallback = "defaultmethod") public class ConsumerController { //注入接口 @Autowired Userclient userclient; // @Autowired // private RestTemplate restTemplate; // @Autowired // private RibbonLoadBalancerClient client; @RequestMapping("/hello/{id}") @ResponseBody public User query(@PathVariable("id") int id){ // ServiceInstance instanceInfo=client.choose("user-service"); // List<ServiceInstance> list=discoveryClient.getInstances("USER-SERVER"); // ServiceInstance instanceInfo=list.get(0) // String url="http://"+instanceInfo.getHost()+":"+instanceInfo.getPort()+"/hello"; User user= userclient.querybyid(id); return user; } private String queryfallback(){//方法的参数要和 return "不好意思,服务拥挤!"; } public String defaultmethod(){ return "不好意思,服务拥挤!"; } }就可以实现调用了