Spring Cloud Feign提供了继承特性,可以进一步减少编码量,并提高可读性。
创建api工程:
命名为hello-service-api
pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zsy</groupId>
<artifactId>zsy-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>hello-service-api</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
</project>
编写实体类User
public class User {
private String name;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
编写HelloService接口:
@RequestMapping("/hello")
public interface HelloService {
@RequestMapping(value = "/test1", method = RequestMethod.GET)
String test1(@RequestParam("name") String name) ;
@RequestMapping(value = "/test2", method = RequestMethod.POST)
String test2(@RequestBody User user);
}
编写hello-service
pom.xml增加依赖:
<dependency>
<groupId>com.zsy</groupId>
<artifactId>hello-service-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
创建HelloController接口,实现hello-service-api中定义的接口HelloService
@RestController
public class HelloController implements HelloService {
@Override
public String test(@RequestParam("name") String name) {
return "Hello " + name;
}
@Override
public String test2(@RequestBody User user) {
return "Hello "+ user.getName() + ", " + user.getAge();
}
}
通过实现的方式,在Controller中不再包含以往会定义的请求映射注解@RequestMapping,在重写的时候会自动将注解带过来。在这个类中,除了实现接口的逻辑之外,只需要增加@RestController注解使该来成为一个REST接口类就可以了。
编写hello-consumer
编写RefactorHelloService接口,并继承hello-service-api包中的HelloService接口,然后添加@FeignClient注解来绑定服务。
@FeignClient(value = "HELLO-SERVICE")
public interface RefactorHelloService extends com.zsy.service.HelloService {
}
Controller类:
@RestController
public class ConsumerController {
@Autowired
RefactorHelloService refactorHelloService;
@RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
public String helloConsumer() {
String result = refactorHelloService.test1("name");
return result;
}
}
上面例子为feign的继承特性调用服务,对比原本调用方式可减少代码和增加可读性,可维护性。