我使用的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的負載均衡