我使用的SpringCloud版本为Hoxton.SR3
服务消费方使用
第一步:引入Feign依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
第二步:启用Feign,在启动类添加开启的注解
package com.company; 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.netflix.ribbon.RibbonClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; //@EnableDiscoveryClient //启用Eureka客户端 //@SpringBootApplication //@EnableCircuitBreaker //启用Hystrix熔断功能 @SpringCloudApplication //替代以上三个注解 @EnableFeignClients //启用Feign public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class); } //启用Feign以后无需再注入 // @Bean // @LoadBalanced // public RestTemplate restTemplate(){ // return new RestTemplate(); // } }
第三步:写一个Feign的客户端
package com.company.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("user-service")//声明这是一个Feign的客户端接口,value指明服务id public interface UserFeignClient { //使用SpringMVC的注解指明请求方式、请求路径、请求参数和响应类型 @GetMapping("/user/{id}") public String getUserById(@PathVariable(name = "id") Long id); }
第四步:改造消费方的调用方式
package com.company.controller; import com.company.client.UserFeignClient; import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/consumer3")//Feign @Slf4j @DefaultProperties(defaultFallback = "getUserByIdFallBack") public class ConsumerController3 { @Autowired private UserFeignClient feignClient; @GetMapping("/{id}") @HystrixCommand public String getUserById(@PathVariable("id")Long id){ long start=System.currentTimeMillis(); String user = feignClient.getUserById(id); long end=System.currentTimeMillis(); log.debug("调用时长:{}",end-start); return user; } public String getUserByIdFallBack(){ return "很抱歉,服务器3正忙,请稍后再试。"; } }
熔断依旧可用。
Feign内部已经使用了Ribbon的负载均衡