服务间的相互调用之feign
上一篇文章,讲述了通过restTemplate+ribbon去消费服务,这篇文章主要讲述通过feign去消费服务。
一、Feign简介
Feign是一个声明式的web服务客户端,它使得写web服务变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,包括Feign 注解和JAX-RS注解。Feign同时支持可插拔的编码器和解码器。Spring cloud对Spring mvc添加了支持,同时在spring web中次用相同的HttpMessageConverter。当我们使用feign的时候,spring cloud 整和了Ribbon和eureka去提供负载均衡。
简而言之:
- feign采用的是接口加注解
- feign 整合了ribbon
二、准备工作
继续用上一节的工程: 启动eureka-server,端口为8761; 启动service-hi 两次,端口分别为8762 、8773.
三、创建一个feign的服务
创建一个spring-boot工程,取名为:serice-feign,它的pom文件为:
4.0.0
com.forezp
service-feign
0.0.1-SNAPSHOT
jar
service-feign
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
UTF-8
UTF-8
1.8
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.cloud
spring-cloud-starter-feign
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
Dalston.RC1
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
向服务注册中心注册它自己,这时service-ribbon既是服务提供者,也是服务消费者,配置文件application.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8765
spring:
application:
name: service-feign
在程序的入口类,需要通过注解@EnableFeignClients来开启feign:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
定义一个feign接口类,通过@ FeignClient(“服务名”),来指定调用哪个服务:
/**
* Created by fangzhipeng on 2017/4/6.
*/
@FeignClient(value = "service-hi")
public interface SchedualServiceHi {
@RequestMapping(value = "/hi",method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
在web层的controllrt:
@RestController
public class HiController {
@Autowired
SchedualServiceHi schedualServiceHi;
@RequestMapping(value = "/hi",method = RequestMethod.GET)
public String sayHi(@RequestParam String name){
return schedualServiceHi.sayHiFromClientOne(name);
}
}
访问http://localhost:8765/hi?name=forezp,浏览器交替显示:
hi forezp,i am from port:8762
hi forezp,i am from port:8763
四、更改feign的配置
在声明feignclient的时候,不仅要指定服务名,同时需要制定服务配置类:
@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}
重写配置,需要加@Configuration注解,并重写下面的两个bean,栗子:
@Configuration
public class FooConfiguration {
@Bean
public Contract feignContractg() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
}
本文源码下载:
https://github.com/forezp/SpringCloudLearning/tree/master/chapter3
五、参考资料
spring-cloud-feign