首页
统计
关于
Search
1
Sealos3.0离线部署K8s集群
1,308 阅读
2
类的加载
864 阅读
3
Spring Cloud OAuth2.0
857 阅读
4
SpringBoot自动装配原理
747 阅读
5
集合不安全问题
646 阅读
笔记
Java
多线程
注解和反射
JVM
JUC
设计模式
Mybatis
Spring
SpringMVC
SpringBoot
MyBatis-Plus
Elastic Search
微服务
Dubbo
Zookeeper
SpringCloud
Nacos
Sentinel
数据库
MySQL
Oracle
PostgreSQL
Redis
MongoDB
工作流
Activiti7
Camunda
消息队列
RabbitMQ
前端
HTML5
CSS
CSS3
JavaScript
jQuery
Vue2
Vue3
Canvas
Linux
容器
Docker
Containerd
Podman
Kubernetes
Python
FastApi
OpenCV
数据分析
牛牛生活
登录
Search
标签搜索
Java
CSS
mysql
RabbitMQ
JavaScript
Redis
OpenCV
JVM
Mybatis-Plus
Camunda
多线程
CSS3
Python
Canvas
Spring Cloud
注解和反射
Activiti
工作流
SpringBoot
ndarray
蘇阿細
累计撰写
452
篇文章
累计收到
4
条评论
首页
栏目
笔记
Java
多线程
注解和反射
JVM
JUC
设计模式
Mybatis
Spring
SpringMVC
SpringBoot
MyBatis-Plus
Elastic Search
微服务
Dubbo
Zookeeper
SpringCloud
Nacos
Sentinel
数据库
MySQL
Oracle
PostgreSQL
Redis
MongoDB
工作流
Activiti7
Camunda
消息队列
RabbitMQ
前端
HTML5
CSS
CSS3
JavaScript
jQuery
Vue2
Vue3
Canvas
Linux
容器
Docker
Containerd
Podman
Kubernetes
Python
FastApi
OpenCV
数据分析
牛牛生活
页面
统计
关于
搜索到
452
篇与
的结果
2021-05-05
Seata
seata是一个分布式的解决方案,致力于在微服务架构下提供高性能和简单易用的分布式微服务,官网:http://seata.io/zh-cn/一、三组概念TC 事务协调者:维护全局和分支事务的状态,驱动全局事务提交或回滚TM 事务管理器:定义全局事务的范围:开始、提交、回滚RM 资源管理器:管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚二、安装GitHub地址:https://github.com/seata/seata(以Nacos 2.0、Seata 1.4.2为例)修改配置文件1、/conf/file.conf (注意与1.0之前的版本区分,1.0之后可以在yml文件中指定service配置)修改数据库模式(使用数据库存储事务信息)和数据源2、/conf/registry.conf3、mysql建表1、新建seata数据库2、运行mysql.sql注意:建表sql在/conf/REDME.md文件中,点击server出现存放sql的github地址:https://github.com/seata/seata/tree/develop/script/server4、启动先启动Nacos再启动Seata(bin/seata-server.bat)三、业务测试1、业务说明创建三个微服务:订单---库存---账户大致流程:当用户下单时,订单服务创建订单,远程调用库存服务扣减库存,再通过远程调用账户服务来扣减账户余额,最后在订单服务中修改订单状态为已完成。2、数据库建表创建三个数据库seata_order(订单),seata_storage(库存),seata_account(账户)创建对应的表-- t_order DROP TABLE IF EXISTS `t_order`; CREATE TABLE `t_order` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `user_id` bigint(11) NULL DEFAULT NULL COMMENT '用户id', `product_id` bigint(11) NULL DEFAULT NULL COMMENT '产品id', `count` int(11) NULL DEFAULT NULL COMMENT '数量', `money` decimal(11, 0) NULL DEFAULT NULL COMMENT '金额', `status` int(1) NULL DEFAULT NULL COMMENT '订单状态:0:创建中; 1:已完结', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- t_storage DROP TABLE IF EXISTS `t_storage`; CREATE TABLE `t_storage` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `product_id` bigint(11) NULL DEFAULT NULL COMMENT '产品id', `total` int(11) NULL DEFAULT NULL COMMENT '总库存', `used` int(11) NULL DEFAULT NULL COMMENT '已用库存', `residue` int(11) NULL DEFAULT NULL COMMENT '剩余库存', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; INSERT INTO `t_storage` VALUES (1, 1, 100, 0, 100); -- t_account DROP TABLE IF EXISTS `t_account`; CREATE TABLE `t_account` ( `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `user_id` bigint(11) NULL DEFAULT NULL COMMENT '用户id', `total` decimal(10, 0) NULL DEFAULT NULL COMMENT '总额度', `used` decimal(10, 0) NULL DEFAULT NULL COMMENT '已用余额', `residue` decimal(10, 0) NULL DEFAULT 0 COMMENT '剩余可用额度', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; INSERT INTO `t_account` VALUES (1, 1, 1000, 0, 1000);undo回滚日志表,三个库每个都需要创建一张回滚表,分别执行三次DROP TABLE IF EXISTS `undo_log`; CREATE TABLE `undo_log` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `branch_id` bigint(20) NOT NULL, `xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `rollback_info` longblob NOT NULL, `log_status` int(11) NOT NULL, `log_created` datetime(0) NOT NULL, `log_modified` datetime(0) NOT NULL, `ext` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;3、seata-order-servicepom<dependencies> <!-- API --> <dependency> <groupId>com.sw</groupId> <artifactId>cloud-api-commons</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!--nacos--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--seata--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> <exclusions> <exclusion> <artifactId>seata-all</artifactId> <groupId>io.seata</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.seata</groupId> <artifactId>seata-spring-boot-starter</artifactId> <version>1.4.0</version> </dependency> <!--feign--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--web-actuator--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--mysql-druid--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.16</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>ymlserver: port: 2001 spring: application: name: seata-order-service cloud: nacos: discovery: server-addr: localhost:8848 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/seata_order?useSSL=true&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 username: root password: 123456 seata: enabled: true application-id: ${spring.application.name} # 自定义事务组名称 tx-service-group: test_tx_group service: vgroup-mapping: test_tx_group: default config: nacos: namespace: server-addr: 127.0.0.1:8848 group: SEATA_GROUP userName: "nacos" password: "nacos" registry: type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 namespace: userName: "nacos" password: "nacos" feign: hystrix: enabled: false logging: level: io: seata: info启动类@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //取消自动创建数据源 @EnableDiscoveryClient @EnableFeignClients @MapperScan("com.sw.mapper") public class SeataOrderMain2001 { public static void main(String[] args) { SpringApplication.run(SeataOrderMain2001.class, args); } }pojo@Data @NoArgsConstructor @AllArgsConstructor public class Order implements Serializable { private Long id; private Long userId; private Long productId; private Integer count; private BigDecimal money; private Integer status; //订单状态:0:创建中;1:已完结 }mapper@Repository public interface OrderMapper { /** * 新建订单 * @param order */ @Insert("insert into t_order(id,user_id,product_id,count,money,status) " + "values(null,#{userId},#{productId},#{count},#{money},0)") void create(Order order); /** * 更新订单 * @param userId * @param status */ @Update("update t_order set status = 1 " + "where user_id=#{userId} and status = #{status}") void update(@Param("userId")Long userId, @Param("status")Integer status); }serviceOrderServicepublic interface OrderService { void create(Order order); }StorageService@FeignClient("seata-storage-service") public interface StorageService { @PostMapping("/storage/decrease") CommonResult decrease(@RequestParam("productId")Long productId, @RequestParam("count")Integer count); }AccountService@FeignClient("seata-account-service") public interface AccountService { @PostMapping("/account/decrease") CommonResult decrease(@RequestParam("userId")Long userId, @RequestParam("money")BigDecimal money); }service实现@Service @Slf4j public class OrderServiceImpl implements OrderService { @Autowired private OrderMapper orderMapper; @Autowired private AccountService accountService; @Autowired private StorageService storageService; @Override public void create(Order order) { //1.新建订单 log.info("===开始新建订单==="); orderMapper.create(order); //2.扣减库存 log.info("===订单微服务调用库存==="); storageService.decrease(order.getProductId(), order.getCount()); log.info("===订单微服务调用库存,库存数量操作结束==="); //3.扣减账户 log.info("===订单微服务调用账户余额==="); accountService.decrease(order.getUserId(), order.getMoney()); log.info("===订单微服务调用账户余额,账户余额操作结束==="); //4.修改订单状态 log.info("===修改订单状态,开始==="); //从 0 到 1,1代表已经完成 orderMapper.update(order.getUserId(), 0); log.info("===修改订单状态,操作结束==="); log.info("订单操作完成(*^_^*)"); } }controller@RestController @RequestMapping("/order") public class OrderController { @Autowired private OrderService orderService; @GetMapping("/create") public CommonResult create(Order order){ orderService.create(order); return new CommonResult(200, "订单创建成功!"); } } config主启动类排除了数据源配置,此处需指定数据源代理@Configuration public class DataSourceProxyConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource(){ return new DruidDataSource(); } @Primary @Bean("dataSource") public DataSourceProxy dataSourceProxy(DataSource dataSource){ return new DataSourceProxy(dataSource); } }4、seata-storage-serviceymlserver: port: 2002 spring: application: name: seata-storage-service cloud: nacos: discovery: server-addr: localhost:8848 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/seata_storage?useSSL=true&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 username: root password: 123456 seata: enabled: true application-id: ${spring.application.name} tx-service-group: test_tx_group service: vgroup-mapping: test_tx_group: default config: nacos: namespace: server-addr: 127.0.0.1:8848 group: SEATA_GROUP userName: "nacos" password: "nacos" registry: type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 namespace: userName: "nacos" password: "nacos" feign: hystrix: enabled: false logging: level: io: seata: infomapper@Repository public interface StorageMapper { /** * 扣减库存信息 * @param productId * @param count */ @Update("update t_storage " + "set used = used + #{count}," + "residue = residue - #{count} "+ "where product_id = #{productId}" ) void decrease(@Param("productId")Long productId, @Param("count")Integer count); }servicepublic interface StorageService { void decrease(Long productId, Integer count); }service实现@Slf4j @Service public class StorageServiceImpl implements StorageService { @Autowired private StorageMapper storageMapper; @Override public void decrease(Long productId, Integer count) { log.info("===storage-service 开始扣减库存==="); storageMapper.decrease(productId, count); log.info("===storage-service 扣减库存操作结束==="); } }其他配置同理order微服务模块的5、seata-account-servicemapper@Repository public interface AccountMapper { /** * 扣减账户余额 * @param userId * @param money */ @Update("update t_account set "+ "used = used + #{money},"+ "residue = residue - #{money} "+ "where user_id = #{userId}" ) void decrease(@Param("userId")Long userId, @Param("money") BigDecimal money); }其他配置同理storage微服务模块的创建6、不添加全局事务管理测试seata-account-service模块1、手动模拟超时@Slf4j @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountMapper accountMapper; @Override public void decrease(Long userId, BigDecimal money) { log.info("===account-service 开始扣减账户余额==="); //模拟超时异常 try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } accountMapper.decrease(userId, money); log.info("===account-service 扣减账户余额操作结束==="); } }浏览器输入http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100报错Read TimeOut异常:此时数据库的状态:7、开启全局事务在order模块中添加全局事务注解@GlobalTransactional使用同样的方法测试,发生调用超时异常后,数据库中被修改的数据回滚到了操作之前的状态
2021年05月05日
77 阅读
0 评论
0 点赞
2021-04-29
Sentinel规则持久化
默认规则是临时存储的,重启Sentinel服务之后消失1、环境搭建以8401模块为例添加pom依赖<!-- datasource-nacos --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency>ymlserver: port: 8401 spring: application: name: cloud-alibaba-sentinel-service cloud: nacos: discovery: server-addr: localhost:8848 sentinel: transport: # sentinel dashboard地址 dashboard: localhost:8080 # 默认8719端口,如果8719被占用,默认递增 port: 8719 # 流控规则持久化 datasource: ds1: nacos: server-addr: localhost:8848 # namespace根据具体的情况指定 dataId: cloud-alibaba-sentinel-service groupId: DEFAULT_GROUP data-type: json rule-type: flow management: endpoints: web: exposure: include: '*'Nacos新建配置文件参数说明:resource:资源名称limitApp:应用来源grade:阈值类型,0:线程数,1:QPScount:单机阈值strategy:流控模式,0:直接,1:关联,2:链路controBehavier:流控效果,0:快速失败,1:Warm Up,2:排队等待clusterMode:是否集群2、测试1、启动8401,在Sentinel控制中心可以看到读取了Nacos那边配置的流控规则;2、关闭8401,Sentinel控制中心的规则消失;3、重启8401,重启之后如果出现了流控规则,则表明规则持久化配置成功。图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
2021年04月29日
147 阅读
0 评论
0 点赞
2021-04-29
Sentinel整合Open Feign
1、环境搭建以8884模块为例pom文件添加依赖<!-- openfign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>yml添加# 激活sentinel对feign的支持 feign: sentinel: enabled: true启动类@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class OrderMain84 { public static void main(String[] args) { SpringApplication.run(OrderMain84.class, args); } }创建远程调用接口@FeignClient(value = "nacos-payment-provider") public interface PaymentService { @GetMapping("/payment/{id}") public CommonResult<Payment> payment(@PathVariable("id")Long id); }实现类(用于服务降级)@Component public class PaymentFallbackService implements PaymentService { @Override public CommonResult<Payment> payment(Long id) { return new CommonResult<Payment>(444, "服务降级返回--PaymentService", new Payment(id, "errorSerial")); } }接口指定降级的类@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class) public interface PaymentService { @GetMapping("/payment/{id}") public CommonResult<Payment> payment(@PathVariable("id")Long id); }controller@Resource private PaymentService service; @GetMapping("/payment/{id}") public CommonResult<Payment> payment(@PathVariable("id")Long id){ return service.payment(id); }2、测试启动9003、8884,如果中途9003出现问题关闭,8884服务降级成功3、熔断框架比较 SentinelHystrixresilience4j隔离策略信号量隔离线程池/信号量隔离信号量隔离熔断降级策略基于响应时间、异常比例、异常数异常比例异常比例、响应时间实时统计滑动窗口(LeapArray)滑动窗口(Rxjava)Ring Bit Buffer动态规则支持多种数据源支持多种数据源有限的支持扩展性多个扩展点插件接口基于注解的支持支持支持支持限流QPS、调用关系有限的支持Rate Limiter图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
2021年04月29日
316 阅读
0 评论
0 点赞
2021-04-29
服务熔断
1、环境搭建1、启动Nacos、Sentinel2、新建9003、9004两个模块pom<!-- API --> <dependency> <groupId>com.sw</groupId> <artifactId>cloud-api-commons</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- Nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency>ymlserver: port: 9003 spring: application: name: nacos-payment-provider cloud: nacos: discovery: server-addr: localhost:8848 management: endpoints: web: exposure: include: '*'启动类@SpringBootApplication @EnableDiscoveryClient public class PaymentMain9003 { public static void main(String[] args) { SpringApplication.run(PaymentMain9003.class, args); } }controller(此处的虚拟数据库是为了方便演示)@RestController @RequestMapping("/payment") public class PaymentController { @Value("${server.port}") private String serverPort; public static Map<Long, Payment> map = new HashMap<>(); static { map.put(1L, new Payment(1L, "螺蛳粉01")); map.put(2L, new Payment(2L, "螺蛳粉02")); map.put(3L, new Payment(3L, "螺蛳粉03")); } @GetMapping("/{id}") public CommonResult<Payment> payment(@PathVariable("id")Long id){ Payment payment = map.get(id); CommonResult<Payment> result = new CommonResult<>(200, "serverPort: " + serverPort, payment); return result; } }注:9004构建步骤与9003一致2、新建8884模块pom同理9004、9004模块ymlserver: port: 8884 spring: application: name: nacos-order-consumer cloud: nacos: discovery: server-addr: localhost:8848 sentinel: transport: # sentinel dashboard地址 dashboard: localhost:8080 # 默认8719端口,如果8719被占用,默认递增 port: 8719 service-url: nacos-user-service: http://nacos-payment-provider management: endpoints: web: exposure: include: '*'启动类@SpringBootApplication @EnableDiscoveryClient public class OrderMain84 { public static void main(String[] args) { SpringApplication.run(OrderMain84.class, args); } }config配置类@Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } }controller@RestController @RequestMapping("/consumer") public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Autowired private RestTemplate restTemplate; @GetMapping(value = "fallback/{id}", produces = {"application/json;charset=UTF-8"}) @SentinelResource("fallback") public CommonResult<Payment> fallback(@PathVariable("id")Long id){ CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, CommonResult.class, id); if (id ==4){ throw new IllegalArgumentException("参数异常!"); }else if (result.getData() == null){ throw new NullPointerException("没有找到对应id的记录!"); } return result; } }指定降级方法@RestController @RequestMapping("/consumer") public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Autowired private RestTemplate restTemplate; @GetMapping(value = "fallback/{id}", produces = {"application/json;charset=UTF-8"}) //@SentinelResource("fallback") @SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback只负责业务异常 public CommonResult<Payment> fallback(@PathVariable("id")Long id){ CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, CommonResult.class, id); if (id ==4){ throw new IllegalArgumentException("参数异常!"); }else if (result.getData() == null){ throw new NullPointerException("没有找到对应id的记录!"); } return result; } public CommonResult handlerFallback(@PathVariable("id")Long id, Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444,"handlerFallback,异常内容:" + e.getMessage(), payment); } }2、测试启动测试:注:此处没有使用Sentinel来配置降级规则,但却降级成功,是因为fallback用于管理异常,当业务发生异常时,可以降级到指定的方法为业务添加blockhandler@RestController @RequestMapping("/consumer") public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Autowired private RestTemplate restTemplate; @GetMapping(value = "fallback/{id}", produces = {"application/json;charset=UTF-8"}) //@SentinelResource("fallback") //@SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback只负责业务异常 @SentinelResource(value = "fallback", blockHandler = "blockHandler") //blockHandler只负责sentinel控制台的配置 public CommonResult<Payment> fallback(@PathVariable("id")Long id){ CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, CommonResult.class, id); if (id ==4){ throw new IllegalArgumentException("参数异常!"); }else if (result.getData() == null){ throw new NullPointerException("没有找到对应id的记录!"); } return result; } // public CommonResult handlerFallback(@PathVariable("id")Long id, Throwable e){ // Payment payment = new Payment(id, "null"); // return new CommonResult(444,"handlerFallback,异常内容:" + e.getMessage(), payment); // } public CommonResult blockHandler(@PathVariable("id")Long id, BlockException exception){ Payment payment = new Payment(id, "null"); return new CommonResult(444,"blockHandler,异常内容:" + exception.getMessage(), payment); } }测试结果:注:可以看到返回结果直接报错,并没有降级,所以说blockHandler只适用于Sentinel配置的规则同时配置fallback和blockHandler@RestController @RequestMapping("/consumer") public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Autowired private RestTemplate restTemplate; @GetMapping(value = "fallback/{id}", produces = {"application/json;charset=UTF-8"}) //@SentinelResource("fallback") //@SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback只负责业务异常 //@SentinelResource(value = "fallback", blockHandler = "blockHandler") //blockHandler只负责sentinel控制台的配置 @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler") public CommonResult<Payment> fallback(@PathVariable("id")Long id){ CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, CommonResult.class, id); if (id ==4){ throw new IllegalArgumentException("参数异常!"); }else if (result.getData() == null){ throw new NullPointerException("没有找到对应id的记录!"); } return result; } public CommonResult handlerFallback(@PathVariable("id")Long id, Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444,"handlerFallback,异常内容:" + e.getMessage(), payment); } public CommonResult blockHandler(@PathVariable("id")Long id, BlockException exception){ Payment payment = new Payment(id, "null"); return new CommonResult(444,"blockHandler,异常内容:" + exception.getMessage(), payment); } } 配置Sentinel规则:结果:可以看到,同时配置fallback和blockHandler,blockHandler的优先级更高exceptionsToIgnore属性@RestController @RequestMapping("/consumer") public class CircleBreakerController { public static final String SERVICE_URL = "http://nacos-payment-provider"; @Autowired private RestTemplate restTemplate; @GetMapping(value = "fallback/{id}", produces = {"application/json;charset=UTF-8"}) //@SentinelResource("fallback") //@SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback只负责业务异常 //@SentinelResource(value = "fallback", blockHandler = "blockHandler") //blockHandler只负责sentinel控制台的配置 @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class}) public CommonResult<Payment> fallback(@PathVariable("id")Long id){ CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, CommonResult.class, id); if (id ==4){ throw new IllegalArgumentException("参数异常!"); }else if (result.getData() == null){ throw new NullPointerException("没有找到对应id的记录!"); } return result; } public CommonResult handlerFallback(@PathVariable("id")Long id, Throwable e){ Payment payment = new Payment(id, "null"); return new CommonResult(444,"handlerFallback,异常内容:" + e.getMessage(), payment); } public CommonResult blockHandler(@PathVariable("id")Long id, BlockException exception){ Payment payment = new Payment(id, "null"); return new CommonResult(444,"blockHandler,异常内容:" + exception.getMessage(), payment); } }测试结果:注:使用exceptionsToIgnore指定异常类,表示当前方法如果抛出了指定的异常,不进行降级处理,直接返回抛出的异常结果图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
2021年04月29日
84 阅读
0 评论
0 点赞
2021-04-29
@SentinelResource注解
1、环境搭建(8401模块)8401模块的pom增加以下依赖<!--通用Commons--> <dependency> <groupId>com.sw</groupId> <artifactId>cloud-api-commons</artifactId> <version>1.0-SNAPSHOT</version> </dependency>controller@RestController public class RateLimitController { @GetMapping(value = "/byResource", produces = {"application/json;charset=UTF-8"}) @SentinelResource(value = "byResource", blockHandler = "handlerException") public CommonResult<JSONObject> byResource(){ return new CommonResult(200, "按资源名称测试限流",new Payment(100L, "干脆面")); } public CommonResult<JSONObject> handlerException(BlockException exception){ return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用!"); } }限流规则注:配置了@SentinelResource注解后,资源名填byResource或者/byResource都可以测试2、自定义限流规则单独创建一个handler类,用于处理限流public class CustomerBlockHandler { public static CommonResult handlerException1(BlockException exception){ return new CommonResult(444, "global handlerException01"); } public static CommonResult handlerException2(BlockException exception){ return new CommonResult(444, "global handlerException02"); } }controller指定自定义的降级方法@GetMapping(value = "/customerBlockHandler", produces = {"application/json;charset=UTF-8"}) @SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2" ) public CommonResult<JSONObject> customerBlockHandler(){ return new CommonResult(200, "按客户自定义测试限流",new Payment(100L, "干脆面")); }Sentinel自定义限流规则测试补充3、其他属性@SentinelResource不适用于private方法value:资源名称,必需项(不能为空);entryType:entry类型,可选项(默认为 EntryType.OUT);fallback:fallback函数名称,可选项,用于在抛出异常的时候提供 fallback处理逻辑;fallback函数可以针对所有类型的异常(除了exceptionsToIgnore里面排除掉的异常类型)进行处理。fallback函数签名和位置要求: 返回值类型必须与原函数返回值类型一致;方法参数列表需要和原函数一致,或者可以额外多一个 Throwable类型的参数用于接收对应的异常;fallback函数默认需要和原方法在同一个类中。若希望使用其他类的函数,则可以指定 fallbackClass为对应的类的 Class 对象,注意对应的函数必需为 static函数,否则无法解析。 defaultFallback(since 1.6.0):默认的 fallback函数名称,可选项,通常用于通用的 fallback逻辑(即可以用于很多服务或方法)。默认 fallback函数可以针对所有类型的异常(除了exceptionsToIgnore里面排除掉的异常类型)进行处理。若同时配置了 fallback和 defaultFallback,则只有 fallback会生效。defaultFallback函数签名要求:返回值类型必须与原函数返回值类型一致;方法参数列表需要为空,或者可以额外多一个 Throwable 类型的参数用于接收对应的异常;defaultFallback函数默认需要和原方法在同一个类中。若希望使用其他类的函数,则可以指定 fallbackClass为对应的类的 Class 对象,注意对应的函数必需为 static 函数,否则无法解析;exceptionsToIgnore(since 1.6.0):用于指定哪些异常被排除掉,不会计入异常统计中,也不会进入 fallback 逻辑中,而是会原样抛出。图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
2021年04月29日
216 阅读
0 评论
0 点赞
2021-04-29
系统保护规则
参数说明:LOAD自适应:(仅对Linux/Unix生效)系统的1oad1作为启发指标,进行自适应系统保护。当系统load1超过设定的启发值,且系统当前的并发线程数超过估算的系统容量时才会触发系统保护(BBR阶段),系统容量由maxQps * minRt估算得出,设定的参考值一般为:CPU cores * 2.5RT:单台机器上所有入口流量的平均RT达到阈值,触发系统保护,单位:ms线程数:单台机器上所有入口流量的并发线程数达到阈值,触发系统保护入口QPS:单台机器上所有入口流量的QPS达到阈值,触发系统保护CPU使用率:当系统CPU使用率超过阈值,触发系统保护测试(以入口QPS为例):图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
2021年04月29日
65 阅读
0 评论
0 点赞
2021-04-29
热点规则
热点规则:很多时候我们希望统计数据中访问次数最高的数据,并对其访问进行限制热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值和模式,对包含热点参数的资源调用进行限流(该策略仅对包含热点参数的资源生效)。1、测试:新增测试方法,并自定义降级方法测试结果:带参数p1访问/testHotKey,且每秒钟的请求次数触发了限流规则不带热点参数访问:2、设置热点规则的其他选项测试:测试结果:图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
2021年04月29日
73 阅读
0 评论
0 点赞
2021-04-29
降级规则
Sentinel熔断降级会在调用链路中某个资源出现不稳定状态时(超时或异常),对这个资源的调用进行限制,让请求快速失败,避免影响到其它资源而导致级联错误。 当资源被降级后,在接下来的降级时间窗口内,对该资源的调用都会自动熔断(默认抛出DegradeException异常)。参数说明:RT(平均响应时间,秒级):平均响应时间超出阈值==且==在时间窗口内通过的请求 >= 5,两个条件同时满足后,进行服务降级,时间窗口期过后,关闭断路器RT最大4900ms(更大的值需通过-Dcsp.sentinel.statistic.max.rt=xxx设置)异常比例(秒级):QPS >= 5 ==且==异常比例([0.01-1.0])超过阈值,触发降级,时间窗口结束后,关闭断路器异常数(分钟级):异常数超过阈值时,触发降级,时间窗口结束后,关闭断路器1、RT平均响应时间Sentinel默认设置为1秒5次请求。一秒钟进入5个请求,且平均响应时间超过设置的200ms,就触发降级Jmeter压力测试:新增一个测试方法:2、异常比例 当资源的每秒请求量 >= 5,并且每秒异常总数占总通过请求数的比值超过设置的阈值,触发熔断降级,异常比例阈值范围:[0.01-1.0]测试:修改刚才新增的/testD测试方法设置降级规则:未触发降级的返回结果:触发降级的返回结果:3、异常数 当请求的资源近1分钟的异常数目超过阈值之后,会进行熔断。由于统计时间窗口是分钟级的,如果timeWindow(时间窗口期)小于60s,结束熔断后可能会再次进入熔断状态。
2021年04月29日
183 阅读
0 评论
0 点赞
1
...
28
29
30
...
57