第三篇:服务提供与Feign调用
Feign是一个声明式Web Service客户端。使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡
本篇基于上一篇的项目
创建Feign服务
新建一个model,serice-feign工程,引入feign依赖spring-cloud-starter-openfeign
,eureka客户端
依赖
pom文件如下
<!--Eureka依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--Web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Feign依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
spring-cloud-starter-openfeign: 这个包是springcloud对于Feign的封装,Feign是一个声明式的Web服务客户端。它支持Feign本身的注解、JAX-RS注解以及SpringMVC的注解。
编写配置文件application.yml
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8765 spring: application: name: service-feign
在启动类上加上@EnableFeignClients
注解
@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class ServiceFeignApplication { public static void main(String[] args) { SpringApplication.run(ServiceFeignApplication.class, args); } }
定义一个feign接口ServiceFeignTest接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了service-client服务的“/test”接口,代码如下:
@FeignClient(value = "eureka-client")//name:远程服务名,此类中的方法和远程服务中contoller中的方法名和参数需保持一致 public interface ServiceFeignTest { @RequestMapping(value = "/test", method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
创建controller层FeignTestController,来消费服务
@RestController public class FeignTestController { @Autowired ServiceFeignTest serviceFeignTest; @GetMapping(value = "/test") public String sayHi(@RequestParam String name) { return serviceFeignTest.sayHiFromClientOne(name); } }
依次启动eureka-server,2个service-client,server-feign
多次访问http://localhost:8764/hi?name=haha,会交替显示
hi haha ,现在的端口是:8762 hi haha ,现在的端口是:8763