十二、Sentinel支持OpenFeign
Sentinel要支持OpenFeign,只需要以下两个步骤:
1、配置feign.sentinel.enabled=true
2、添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在Producer模块中定义资源:
@RestController
public class HelloProducer {
@Value("${server.port}")
private int port;
@RequestMapping("/hello")
public String hello() {
return "hello,Producer,port:" + port;
}
}
首先在根项目的dependencyManagement中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.6</version>
</dependency>
其次在Consumer中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在Consumer的application.properties配置:
feign.sentinel.enabled=true
在启动类加@EnableFeignClients。
增加feign接口:
@FeignClient(name = "producer", fallback = HelloFeignFallback.class, configuration = FeignConfiguration.class)
public interface HelloFeign {
@RequestMapping("/hello")
String hello();
}
fallback属性是服务降级的处理。producer是Producer的服务名。
public class HelloFeignFallback implements HelloFeign {
@Override
public String hello() {
return "hello fallback";
}
}
public class FeignConfiguration {
@Bean
public HelloFeign helloFeign() {
return new HelloFeignFallback();
}
}
FeignConfiguration没加@Configuration注解。
在Controller加:
@Autowired
private HelloFeign helloFeign;
@RequestMapping("/call")
public String call() {
return helloFeign.hello();
}
启动Consumer和Producer后,访问http://localhost:7001/consumer/call,看到hello,Producer,port:7000。关闭Producer服务,在调用,看到hello fallback。继续启动一个端口是7002的Producer服务,继续访问,发现hello,Producer,port:7000和hello,Producer,port:7002交替输出,实现了负载均衡。