Spring Cloud 學(xué)習(xí)筆記08----服務(wù)消費者(Feign)(Finchley版本)

概要

接上一篇《Spring Cloud 學(xué)習(xí)筆記06----斷路器(Hystrix)(Finchley版本)》,今天我們來學(xué)習(xí)另外一種服務(wù)調(diào)用方式(Feign),之前我們介紹了 RestTemplate+Ribbon 消費服務(wù)的方式。

Feign簡介

Feign 是一個聲明式的偽Http客戶端,它使得寫Http 客戶端變得更簡單,使用Feign,只需要創(chuàng)建一個接口并注解。它具有可插拔的注解特性,可使用Feign注解和JAX-RS注解,F(xiàn)eign 也支持可插拔的編碼器和解碼器,Spring Cloud 擴展了對Spring MVC的注解支持,在Spring Web 中同樣使用HttpMessageConverters 。Feign 默認集成了Ribbon, 并和Eureka 結(jié)合,默認實現(xiàn)了負載均衡的效果。
簡單來說:

  • Feign 采用的是基于接口的注解
  • Feign 整合了Ribbon, 具有負載均衡的能力
  • 整合了Hystrix,具有熔斷能力。

快速入門

首先,沿用前面的服務(wù)注冊中心(eureka-server)以及服務(wù)提供者(order-provider)。然后新建一個SpringBoot 項目,命名為service-feign。添加依賴

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!--必須添加spring-boot-starter-web,否則注冊失敗-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

然后,在application.yml 加上如下配置,指定端口為8765,服務(wù)名為service-feign:

spring:
  application:
    name: service-feign
eureka:
  client:
    service-url:
#    用于指定注冊中心的地址
      defaultZone: http://localhost:1111/eureka/
server:
  port: 8765

接著,我們在ServiceFeignApplication 中添加@EnableFeignClients以激活Feign。添加@EnableEurekaClient 以開啟負載均衡,使其可以注冊到Eureka 中。

@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class ServiceFeignApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServiceFeignApplication.class, args);
	}

}

接著,我們新建一個接口,用于調(diào)用服務(wù)提供者提供的服務(wù),使用@FeignClient(serviceId = "order-service") 指定調(diào)用的服務(wù)名為order-service。

@FeignClient(serviceId = "order-service")
public interface HelloService {

    @GetMapping(value = "/dc")
    String getOrderService(@RequestParam("name") String name);

}

最后,我們新建一個controller 調(diào)用剛剛新建接口HelloService中的方法,測試下是否可以調(diào)用成功

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;

    @GetMapping("/dc")
    public String getOrderService(String name) {
        return helloService.getOrderService(name);
    }
}

測試結(jié)果,我們啟動兩個order-provider 服務(wù),端口號分別為 8082,8083,
然后,啟動 service-feign, 端口號為:8765,
在Eureka面板中查看
在這里插入圖片描述
訪問http://localhost:8765/dc?name=jay會交替出現(xiàn)如下結(jié)果:

hi: jay;port=8083
hi: jay;port=8082

參考代碼

https://github.com/XWxiaowei/SpringCloud-Learning/tree/master/2-Finchley版教程示例/Chapter6-1

參考文獻

http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html#netflix-feign-starter
https://blog.csdn.net/forezp/article/details/81040965



作者:碼農(nóng)飛哥

微信公眾號:碼農(nóng)飛哥