ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 概述 Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的controller一样.你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做.使用Feign会非常优雅.Feign自动实现了负载均衡. 可以看到feign自动引入了hystrix和ribbon,这两个包都省的去引入了.使用feign负载均衡就不需要配置了,但是熔断需要额外配置.并且跟之前的配置方式不一样. ![](https://box.kancloud.cn/36ea21962f1f4cd0271b15d0b112b24b_1594x1078.png) ## feign的负载均衡 ~~~ ribbon: ConnectionTimeOut: 500 //连接超时(默认1秒),500毫秒没有获取连接就抛出异常 ReadTimeOut: 2000 //读取超时(默认1秒),建立连接,但是超过2秒没有读取到数据也抛出异常 ~~~ ## 导包 ~~~ <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.0.1.RELEASE</version> </dependency> ~~~ ## 启动类加注解 ~~~ package com.like; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; //@SpringBootApplication //@EnableDiscoveryClient //@EnableCircuitBreaker @EnableFeignClients //添加Feign客户端注解 @SpringCloudApplication //可以使用该注解替代上面的三个注解 public class ConsumerServer { public static void main(String[] args) { SpringApplication.run(ConsumerServer.class); } @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } } ~~~ ## 编写feign接口 ~~~ package com.like.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("user-server") //服务名称 public interface UserClient { @GetMapping("/user/{id}") String queryById(@PathVariable("id") Long id); //方法名随意 } ~~~ ## 调用接口 经测试,请求成功. ~~~ @RestController @RequestMapping("/user") @DefaultProperties(defaultFallback = "defaultCallBack") public class UserController { @Autowired private UserClient userClient; @GetMapping("/{id}") public String index(@PathVariable("id") Long id) { return userClient.queryById(id); } } ~~~