Feign简介
Feign是一个声明式的Web服务客户端,使用Feign可使得Web服务客户端的写入更加方便。
它具有可插拔注释支持,包括Feign注解和JAX-RS注解、Feign还支持可插拔编码器和解码器、Spring Cloud增加了对Spring MVC注释的支持,并HttpMessageConverters在Spring Web中使用了默认使用的相同方式。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载平衡的http客户端。
Feign简单使用
使用Feign.builder封装SDK
Feign提供了Feign.builder()客户端的构造方法,可以轻松的访问远程的URL,不依赖其他服务。这种方式的用法是将远程的URL,封装成纯接口SDK,供其他用户或系统使用。
1.添加mvn依赖,只使用Feign的依赖即可
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.5.0</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
2.定义FeignClient接口调用RESTFUL接口
public interface FeignClient {
@RequestLine("GET /user/login")
public String login(@Param("username") String username, @Param("password") String password);
}
- 1
- 2
- 3
- 4
3.封装SDK
public class SDK{
public static void login(String username,String password){
FeignClient feignClient = Feign.builder()
.target(FeignClient.class, "http://localhost");
feignClient.login(username,password);
}
/** 测试*/
public static void main(String[] args) {
login("lsz","lsz");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
使用SpringCloud及Eureka服务管理
这种方式是需要添加SpringCloud组件的一些依赖及注解,还需要依赖Spring的容器管理。
1.添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
2.定义UserFeignClient 接口
与SDK不同的是,接口上需要有FeignClient及Component的注解。@Component的含义是将该组件注册到SpringCloud中,接受Spring容器的管理,使用依赖注入得到该接口的实体;@FeignClient注解中可以指定“name”与“url”,如果程序为Eureka客户端,指定name为服务注册中心的名,会去服务注册中心去查找访问的host地址
@Component //springboot中注册该组件
@FeignClient(name="user-server",url = "http://localhost:8011")
public interface UserFeignClient {
@RequestMapping("/{id}")
public User findByIdFeign(@RequestParam("id") Long id);
}
- 1
- 2
- 3
- 4
- 5
- 6
3.定义访问UserFeignClient的controller
@Component
public class UserServiceImpl implements UserService {
@Autowired
private UserFeignClient userFeignClient;
@Override
public User findByIdFeign(String id) {
User object = this.userFeignClient.findByIdFeign("1111");
return object;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Feign的这两种用法,个人比较喜欢第一种,依赖的少,好管理好测试,不需要起太多的服务。