SpringCloud之Feign
本文内容纲要:
-声明式REST客户端:Feign
Fegin是一个声明似的web服务客户端,它使得编写web服务客户端变得更加容易。使用Fegin创建一个接口并对它进行注解。它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,SpringCloud增加了对SpringMVC的注解,SpringWeb默认使用了HttpMessageConverters,SpringCloud集成Ribbon和Eureka提供的负载均衡的HTTP客户端Feign。
声明式REST客户端:Feign
创建一个maven工程eureka_feign_client,pom文件如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/><!--lookupparentfromrepository-->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
在应用主类中通过@EnableFeignClients注解开启Feign功能,启动文件FeignApplication.java如下:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
publicclassFeignApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(FeignApplication.class,args);
}
}
定义服务接口类UserClient.java,使用@FeignClient("service01")注解来绑定该接口对应service01服务
@FeignClient("service01")
publicinterfaceUserClient{
@RequestMapping(method=RequestMethod.GET,value="/getuser")
publicUsergetuserinfo();
@RequestMapping(method=RequestMethod.GET,value="/getuser")
publicStringgetuserinfostr();
@RequestMapping(method=RequestMethod.GET,value="/info")
publicStringinfo();
}
在web层中调用上面定义的UserClient,具体如下
@RestController
publicclassUserController{
@Autowired
UserClientuserClient;
@RequestMapping(value="/getuserinfo",method=RequestMethod.GET)
publicUsergetuserinfo(){
returnuserClient.getuserinfo();
}
@RequestMapping(value="/getuserinfostr",method=RequestMethod.GET)
publicStringgetuserinfostr(){
returnuserClient.getuserinfostr();
}
@RequestMapping(value="/info",method=RequestMethod.GET)
publicStringinfo(){
returnuserClient.info();
}
}
其实通过Feign封装了HTTP调用服务方法,使得客户端像调用本地方法那样直接调用方法,类似Dubbo中暴露远程服务的方式,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端。
本文内容总结:声明式REST客户端:Feign,
原文链接:https://www.cnblogs.com/senlinyang/p/8595489.html