Feign是整合了Ribbon与Hystrix外,还提供了声明式的Web服务客户端定义方式。采用了声明式API接口的风格,将Java Http客户端绑定到它的内部。Feign的首要目标是将Java Http客户端调用过程变得简单。
>
>org.springframework.cloud >
>spring-cloud-starter-netflix-eureka-client >
>
>
>org.springframework.cloud >
>spring-cloud-starter-openfeign >
>
@EnableFeignClients
@EnableDiscoveryClient
支持服务发现与Feign的支持。
通过@FeignClient
注解 指定服务名来绑定服务;
通过Spring MVC的注解来绑定具体该服务提供的REDT接口。
@FeignClient("eureka-provider")
public interface HelloService {
@RequestMapping("/hello")
String sayHello();
}
以上是 eureka-provider 服务的 /hello 接口。
服务名不区分大小写。
来实现对Feign客户端的调用:
@RestController
public class ConsumerController {
@Autowired
HelloService helloService;
@RequestMapping(value = "/feign-consumer")
public String helloConsumer() {
return helloService.sayHello();
}
}
spring:
application:
name: feign-consumer
eureka:
client:
service-url:
defaultZone: http://localhost:1001/eureka/
server:
port: 1301
真是业务场景,参数及返回值只会更加复杂。为了模拟复杂场景,并实现一定的抽象。
由于service-api中需要定义可同时复用于服务端与客户端的接口,需要用到Spring MVC 的注解,所以pom.xml中需要引入依赖:
>
>org.springframework.boot >
>spring-boot-starter-web >
>
>
>org.projectlombok >
>lombok >
>true >
>
@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class User {
private String name;
private Integer age;
}
@RequestMapping("/refactor")
public interface HelloService {
@RequestMapping(value = "/hello4")
String hello(@RequestParam("name") String name);
@RequestMapping(value = "/hello5")
User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
@RequestMapping(value = "/hello6")
String hello(@RequestBody User user);
}
>
>com.example >
>service-api >
>0.0.1-SNAPSHOT >
>
@RestController
public class RefactorHelloController implements HelloService {
@Override
public String hello(@RequestParam("name") String name){
return "Hello" + name;
}
@Override
public User hello(@RequestHeader("name") String name,@RequestHeader("age") Integer age) {
return new User(name,age);
}
@Override
public String hello(@RequestBody User user) {
return "Hello" + user.getName()+","+user.getName();
}
}
此类中,除要实现接口逻辑外,还需增加 @RestController
注解,使该类成为REST接口类。
>
>com.example >
>service-api >
>0.0.1-SNAPSHOT >
>
@FeignClient(value = "eureka-provider")
public interface RefactorHelloService extends HelloService {
}
注意:
@RestController
public class ConsumerController {
// @Autowired
// HelloService helloService;
@Autowired
RefactorHelloService refactorHelloService;
//
// @RequestMapping(value = "/feign-consumer")
// public String helloConsumer() {
//
// return helloService.sayHello();
// }
@RequestMapping(value = "/helloConsumer1")
public String helloConsumer1() {
StringBuilder sb = new StringBuilder();
sb.append(refactorHelloService.hello(" mimi")).append("\n");
sb.append(refactorHelloService.hello("lk",26)).append("\n");
sb.append(refactorHelloService.hello(new User(" jh",25))).append("\n");
return sb.toString();
}
}