Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果
简而言之:
本系列源码地址:https://github.com/lhmyy521125/toher-springcloud-sample
依旧复制一份第一个工程项目,取名为 toher-springcloud-sample3-feign
按照上一章节我创建service-ribbon子工程的模式,还是继续创建一个module , 取名为:service-feign;在它的pom.xml继承了父pom文件,并引入了以下依赖:
4.0.0
cn.toher
springcloud-sample
1.0-SNAPSHOT
cn.toher
service-feign
0.0.1-SNAPSHOT
service-feign
Demo project for Spring Boot
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
在工程的配置文件application.yml文件,指定程序名为service-feign,端口号为9004,服务注册地址为http://localhost:8761/eureka/ ,代码如下:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 9004
spring:
application:
name: service-feign
在程序的启动类通过 @EnableFeignClients 注解开启 Feign 功能
package cn.toher.servicerfeign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了service-hello服务的“/hello”接口,代码如下:
package cn.toher.servicerfeign.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @Author: 同恒科技-李怀明
* @Date: 2019/10/19 15:26
*/
@FeignClient(value = "service-hello")
public interface HelloFeignService {
@RequestMapping(value = "/hello")
String helloFeign(@RequestParam(value = "name") String name);
}
创建测试用的 Controller
package cn.toher.servicerfeign.controller;
import cn.toher.servicerfeign.service.HelloFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: 同恒科技-李怀明
* @Date: 2019/10/19 10:58
*/
@RestController
public class HelloFeignController {
@Autowired
private HelloFeignService helloFeignService;
@RequestMapping("/helloFeign")
public String helloFeign(String name){
return helloFeignService.helloFeign(name);
}
}
运行该工程,查看注册中心(下图) 证明我们已经创建完成,接下来测试一下;
浏览器中输入:http://localhost:9004/helloFeign?name=feign , 会发现浏览器输出信息中端口号的变化,证明成功
hi feign ,this is Feign Project , i am from port:9001
hi feign ,this is Feign Project , i am from port:9002
结语:本章我们学习了如何使用Feign实现服务与服务的通讯并实现负载均衡,大家可以根据博主的代码样例,进行相关测试学习;
下一篇:使用熔断器Hystrix