首先引入sentinel对应依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
下面是示例service代码,通过openFeign完成服务调用
@Service
public class OrderServiceImpl implements OrderService {
@Qualifier("com.example.orderservice.feign.UserFeign")
@Autowired
private UserFeign userFeign;
@Override
public Order getUserOrder(Integer userId) {
System.out.println("开始服务间调用");
return new Order(userFeign.getUserById(userId),1);
}
}
首先需要配置openFeign的服务调用失败的策略,需要对对应的feign接口实现策略失败类
//需要将这个类注册成为bean
@Component
public class UserFeignHystrixImpl implements UserFeign {
@Override
public User getUserById(Integer userId) {
return new User(500,"已触发服务熔断,稍后再试");
}
}
然后在feign的调用接口处,执行熔断策略实现类(fallback)
@FeignClient(value = "user-service",fallback = UserFeignHystrixImpl.class)
public interface UserFeign {
//这里采用springMVC的接口风格赋能方法,使得这个方法已经变成了服务生产者
@GetMapping("user/getUserById")
User getUserById(@RequestParam("userId") Integer userId);
}
然后需要下载阿里的sentinel-dashboard,启动控制台,并在该服务的配置文件中指定项目对应的控制台面板
spring.cloud.sentinel.transport.dashboard=localhost:8080
至此就可以通过 sentinel-dashboard控制台来指定该服务的熔断触发条件以及规则,接口限流等.