Feign简介
Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign。
运用前面的三个项目基础上给Invoker端添加Feign。
- 添加Feign的maven坐标:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
- 应用主类中通过@EnableFeignClients注解开启Feign功能
:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class InvokerApp {
public static void main(String[] args) {
new SpringApplicationBuilder(InvokerApp.class).web(true).run(args);
}
}
- 定义HelloClient
接口,使用@FeignClient(“Spring-fegin-provider”)注解来绑定该接口对应Spring-fegin-provider服务。
@FeignClient("Spring-fegin-provider")
public interface HelloClient {
@RequestMapping(method = RequestMethod.GET, value="/hello/{name}")
String hello(@PathVariable("name") String name);
@RequestMapping(method = RequestMethod.GET, value="/call/{id}")
Police getPolice(@PathVariable("id") Integer id);
@MyUrl(url = "/hellowd", method = "GET")
String myHello();
}
- @MyUrl为自定义的注解翻译器:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyUrl {
String url();
String method();
}
- 继承SpringMvcContract 原有的翻译器,在SpringMvcContract 基础上实现自己定义的MyUrl
:
public class MyContract extends SpringMvcContract {
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
Annotation annotation, Method method) {
super.processAnnotationOnMethod(data, annotation, method);
// 注解是MyUrl类型的,才处理
if(MyUrl.class.isInstance(annotation)) {
System.out.println("############# 这是自定义翻译器");
MyUrl myUrl = method.getAnnotation(MyUrl.class);
String url = myUrl.url();
String httpMethod = myUrl.method();
data.template().method(httpMethod);
data.template().append(url);
}
}
}
- 自动配置MyContract:
@Configuration
public class MyConfig {
@Bean
public Contract feignContract() {
return new MyContract();
}
}
- 在web层中调用上面定义的TestController :
@RestController
public class TestController {
@Autowired
private HelloClient helloClient;
@RequestMapping(method = RequestMethod.GET, value="/router")
public String router() {
String result = helloClient.hello("jack");
return result;
}
@RequestMapping(method = RequestMethod.GET, value="/police",
produces = MediaType.APPLICATION_JSON_VALUE)
public Police getPolice() {
Police p = helloClient.getPolice(1);
return p;
}
@RequestMapping(method = RequestMethod.GET, value="/myhello")
public String myHello() {
return helloClient.myHello();
}
}