前言:
在添加熔断降级服务的情况下,再进行报警处理
熔断降级服务博客地址:
https://www.cnblogs.com/tianhengblogs/p/12487495.html
前提:
需要安装Redis
1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.修改controller
package cn.theng.order_service.controller; import cn.theng.order_service.domain.ProductOrder; import cn.theng.order_service.service.ProductOrderService; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @RestController @RequestMapping("/api/v1/order") public class ProductOrderController { @Autowired private ProductOrderService productOrderService; @Autowired private StringRedisTemplate redisTemplate; @PostMapping("/test2") @HystrixCommand(fallbackMethod = "getProductFail") public Object test2(@RequestParam("product_id") int productId) { //如果test2内有报错,则会执行getProductFail方法 ProductOrder order = productOrderService.save(1, productId); return "success"; } //方法签名一定要与上面方法保持一致 public Object getProductFail(int productId) { //监控报警 String saveOrderKey = "save-order"; String sendValue = redisTemplate.opsForValue().get(saveOrderKey); //短信服务可能会耗时或者阻塞,这里新开个线程来处理 new Thread( () -> { if (StringUtils.isEmpty(sendValue)) { System.out.println("紧急短信,用户下单失败,请查找原因"); //TODO 发送一个http请求,调用短信服务 //设置Redis时间为20秒后自动清除 redisTemplate.opsForValue().set(saveOrderKey, "save-order-fail",20, TimeUnit.SECONDS); }else { System.out.println("已经发送过短信,20秒内不重复发送"); } }).start(); Map<String, Object> map = new HashMap<>(); map.put("code", -1); map.put("msg", "目前排队人数过多,请稍后再试..."); return map; } }
3.修改application.yml配置
spring:
application:
name: order-service
redis:
database: 0
host: 127.0.0.1
port: 6379
timeout: 2000
4.访问地址
原文:https://www.cnblogs.com/tianhengblogs/p/12489870.html