之前搭建的注册中心:http://blog.csdn.net/chenhaotao/article/details/78677328
服务提供者client:http://blog.csdn.net/chenhaotao/article/details/78677858
服务消费者ribbon:http://blog.csdn.net/chenhaotao/article/details/78678445
之前就使用ribbon搭建了一个服务消费者,今天尝试使用Feign搭建一个服务消费者项目。
Feign介绍
Feign是一个声明式的web service客户端,使用Feign搭建项目十分简便,只需要创建一个接口并注解等几个步骤就可以实现,具有可插拔的注解特性,而且Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
项目大致步骤:
1.新建springboot项目,依赖选择:eureka,feign,web
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.在配置文件application.yml配置项目名称端口和注册中心地址等
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1111/eureka/
server:
port:
spring:
application:
name: service-feign
3.定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务
@FeignClient(value = "SERVICE-HELLO")
public interface TestFeignService {
/**
* @RequestMapping指定调用到服务的那个接口,@RequestParam("name")指定传入的参数名
*/
@RequestMapping(value = "index",method = RequestMethod.GET)
String testEurekaClient(@RequestParam("name")String name);
}
注:虽然在服务提供者client中定义服务项目名称为service-hello,但是通过注册中心url:http://localhost:1111/ 查看到注册的服务名称是以大写形式注册的,所以这里调用服务名字要使用大写SERVICE-HELLO。
4.创建controller类,通过@Autowired注解注入feign接口并调用接口方法实现消费服务方法
@RestController
public class TestFeignController {
@Autowired
private TestFeignService testFeignService;
@RequestMapping(value = "/testFeign",method = RequestMethod.GET)
public String test(@RequestParam String name){
return testFeignService.testEurekaClient(name);
}
}
浏览器url输入:http://localhost:9002/testFeign?name=aaa 可以检查服务消费是否实现
附上项目源码:https://pan.baidu.com/s/1mih58Re