在微服務架構搭建聲明性REST客戶端【feign】。
Feign是一個聲明式的Web服務客戶端。這使得Web服務客戶端的寫入更加方便 要使用Feign創建一個界面並對其進行注釋。它具有可插入注釋支持,包括Feign注釋和JAX-RS注釋。Spring Cloud增加了對Spring MVC注釋的支持,並使用Spring Web中默認使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign時提供負載均衡的http客戶端。
有關Feign做微服務降級處理的文章請看上海尚學堂《Hystrix在Fegin做服務降級處理》。
如何加入Feign
第一步
加入feign的Jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
第二步
修改配置文件application.yml
spring:
application:
name: microservice-consumer-movie
server:
port: 7901
eureka:
client:
healthcheck:
enabled: true
serviceUrl:
defaultZone: http://user:password123@localhost:8761/eureka
instance:
prefer-ip-address: true
第三步
添加fegin客戶端接口
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.yonggan.entity.User;
@FeignClient("microservice-provider-user") // 服務名稱
public interface UserFeignClient {
@RequestMapping(value = "/simple/{id}" ,method = RequestMethod.GET)
User findById(@PathVariable("id") Long id);
}
第四步
添加fegin 接口注入到我們web接口層那使用。
@RestController
public class MovieController {
/**
* 添加fegin 遠程的客戶端
* 了解更多微信:java8733
*/
@Autowired
private UserFeignClient feignClient;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return feignClient.findById(id);
}
}
上述就是我們快速的搭建Fegin環境的demo,由上海尚學堂java老師提供支持,感謝!
