006 springCloudAlibaba seata

文章目录

    • undo_log.sql
    • product.sql
    • myorder.sql
    • seata-server-1.5.2
      • application.yml
    • nacos配置列表
      • Data ID: orderServer-dev.yaml
      • Data ID:productServer-dev.yaml
      • DataID:gatewayServer-dev.yaml
      • Data ID: seataServer
    • gatewayServer
      • GatewayServerApplication.java
      • ServletInitializer.java
      • bootstrap.yaml
      • pom.xml
    • orderServer
      • MyorderController.java
      • ProductClient.java
      • Myorder.java
      • MyorderMapper.java
      • MyorderServiceImpl.java
      • IMyorderService.java
      • OrderServerApplication.java
      • ServletInitializer.java
      • bootstrap.yaml
      • pom.xml
      • MyorderMapper.xml
    • productServer
      • ProductController.java
      • Product.java
      • ProductMapper.java
      • ProductServiceImpl.java
      • IProductService.java
      • ProductServerApplication.java
      • ServletInitializer.java
      • ProductMapper.xml
      • bootstrap.yaml
      • pom.xml
    • pom.xml

undo_log.sql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log`  (`id` bigint(0) NOT NULL AUTO_INCREMENT,`branch_id` bigint(0) NOT NULL,`xid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,`context` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,`rollback_info` longblob NOT NULL,`log_status` int(0) NOT NULL,`log_created` datetime(0) NOT NULL,`log_modified` datetime(0) NOT NULL,`ext` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE,UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1;

product.sql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`  (`product_id` int(0) NOT NULL AUTO_INCREMENT,`product_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`product_price` decimal(10, 2) NULL DEFAULT NULL,`product_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`product_count` int(0) NULL DEFAULT NULL,`create_time` datetime(0) NULL DEFAULT NULL,`update_time` datetime(0) NULL DEFAULT NULL,PRIMARY KEY (`product_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of product
-- ----------------------------SET FOREIGN_KEY_CHECKS = 1;

myorder.sql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for myorder
-- ----------------------------
DROP TABLE IF EXISTS `myorder`;
CREATE TABLE `myorder`  (`order_id` int(0) NOT NULL AUTO_INCREMENT,`order_number` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`customer_id` int(0) NULL DEFAULT NULL,`pro_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`pro_id` int(0) NULL DEFAULT NULL,`pro_price` decimal(10, 2) NULL DEFAULT NULL,`pro_main_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`pro_buy_count` int(0) NULL DEFAULT NULL,`order_price` decimal(10, 2) NULL DEFAULT NULL,`order_create_time` datetime(0) NULL DEFAULT NULL,`order_update_time` datetime(0) NULL DEFAULT NULL,`order_status` int(0) NULL DEFAULT NULL,PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of myorder
-- ----------------------------SET FOREIGN_KEY_CHECKS = 1;

seata-server-1.5.2

application.yml


server:port: 7091spring:application:name: seataServerlogging:config: classpath:logback-spring.xmlfile:path: ${user.home}/logs/seataextend:logstash-appender:destination: 127.0.0.1:4560kafka-appender:bootstrap-servers: 127.0.0.1:9092topic: logback_to_logstashconsole:user:username: seatapassword: seataseata:config:# support: nacos, consul, apollo, zk, etcd3type: nacosnacos:namespace:group: DEFAULTGROUPdata-id: seataServer.propertiesusername: password:server-addr: http://127.0.0.1:8848registry:# support: nacos, eureka, redis, zk, consul, etcd3, sofatype: nacosstore:# support: file 、 db 、 redismode: db
#  server:
#    service-port: 8091 #If not configured, the default is '${server.port} + 1000'security:secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017tokenValidityInMilliseconds: 1800000ignore:urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login

nacos配置列表

Data ID: orderServer-dev.yaml

Group:DEFAULT_GROUP


server:port: 9001spring:application:name: orderServerdatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/cloud_order_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456cloud:nacos:server-addr: localhost:8848 # ?????URLsentinel:transport:dashboard: localhost:8080 #??Sentinel dashboard??port: 8719management:endpoints:web:exposure:include: '*'feign:sentinel:enabled: true # ??Sentinel?Feign???
seata:tx-service-group: fsp_tx_groupregistry:type: nacosnacos:server-addr: localhost:8848service:vgroup-mapping:fsp_tx_group: default

Data ID:productServer-dev.yaml

Group:DEFAULT_GROUP

server:port: 7001spring:application:name: productServerdatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/cloud_product_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456cloud:nacos:server-addr: localhost:8848  # ???? nacos ???sentinel:transport:dashboard: localhost:8080 #??Sentinel dashboard??port: 8719management:endpoints:web:exposure:include: '*'feign:sentinel:enabled: true # ??Sentinel?Feign???

DataID:gatewayServer-dev.yaml

Group:DEFAULT_GROUP


server:port: 9090
spring:application:name: gatewayServercloud:nacos:  # nacos urldiscovery:server-addr: localhost:8848sentinel: #sentinel urltransport:dashboard: localhost:8080gateway:   # gatewaydiscovery:locator:enabled: true #??gateway?nacos???????routes:- id: order_routeuri: lb://orderServer # ??orderServer???????????Nacos???predicates:- Path=/order/**- Method=GET,POST- Before=2025-07-09T17:42:47.789-07:00[Asia/Shanghai]- id: product_routeuri: lb://productServer # ??productServer???????????Nacos???predicates:- Path=/product/**feign:sentinel:enabled: true

Data ID: seataServer

Group: DEFAULTGROUP


service.vgroupMapping.fsp_tx_group=default
service.vgroupMapping.fsp_tx_group=default
service.vgroupMapping.fsp_tx_group=defaultstore.mode=dbstore.redis.host=127.0.0.1
store.redis.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.database=0
store.redis.queryLimit=100#store.lock.mode=db
#store.session.mode=db
#store.publicKey=store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://localhost:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000

gatewayServer

GatewayServerApplication.java

package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class GatewayServerApplication {public static void main(String[] args) {SpringApplication.run(GatewayServerApplication.class, args);}}

ServletInitializer.java

package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(GatewayServerApplication.class);}}

bootstrap.yaml

spring:application:name: gatewayServerprofiles:active: devcloud:nacos:config:server-addr: localhost:8848file-extension: yaml

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.example</groupId><artifactId>springCloudAlibaba</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.example</groupId><artifactId>gatewayServer</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>gatewayServer</name><description>gatewayServer</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--SpringCloud ailibaba sentinel --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><!--openfeign--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

orderServer

MyorderController.java


package com.example.controller;import com.example.entity.Myorder;
import com.example.service.IMyorderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;/*** <p>*  前端控制器* </p>** @author dd* @since 2024-05-06*/
@RestController
@RequestMapping("order")
public class MyorderController {@Value("${server.port}") //${} 从yaml文件中获得key-valueprivate int serverPort;@Autowiredprivate IMyorderService myorderService;// 下订单@PostMappingpublic String save(Myorder myorder){boolean result =  myorderService.save(myorder);System.out.println("OrderController 下订单:"+ result);return "订单服务"+serverPort+"正在下订单";}}

ProductClient.java

package com.example.controller;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@FeignClient("productServer")
public interface ProductClient {@GetMapping("product/{proId}")public String getProductById(@PathVariable("proId") Integer proId);// 减库存@GetMapping("product/decrCount/{proId}/{decrCount}")public String decrCount(@PathVariable("proId") Integer proId,@PathVariable("decrCount") Integer decrCount );}

Myorder.java

package com.example.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;/*** <p>* * </p>** @author dd* @since 2024-05-06*/
public class Myorder implements Serializable {private static final long serialVersionUID = 1L;@TableId(value = "order_id", type = IdType.AUTO)private Integer orderId;private String orderNumber;private Integer customerId;private String proName;private Integer proId;private BigDecimal proPrice;private String proMainImg;private Integer proBuyCount;private BigDecimal orderPrice;private LocalDateTime orderCreateTime;private LocalDateTime orderUpdateTime;private Integer orderStatus;public Integer getOrderId() {return orderId;}public void setOrderId(Integer orderId) {this.orderId = orderId;}public String getOrderNumber() {return orderNumber;}public void setOrderNumber(String orderNumber) {this.orderNumber = orderNumber;}public Integer getCustomerId() {return customerId;}public void setCustomerId(Integer customerId) {this.customerId = customerId;}public String getProName() {return proName;}public void setProName(String proName) {this.proName = proName;}public Integer getProId() {return proId;}public void setProId(Integer proId) {this.proId = proId;}public BigDecimal getProPrice() {return proPrice;}public void setProPrice(BigDecimal proPrice) {this.proPrice = proPrice;}public String getProMainImg() {return proMainImg;}public void setProMainImg(String proMainImg) {this.proMainImg = proMainImg;}public Integer getProBuyCount() {return proBuyCount;}public void setProBuyCount(Integer proBuyCount) {this.proBuyCount = proBuyCount;}public BigDecimal getOrderPrice() {return orderPrice;}public void setOrderPrice(BigDecimal orderPrice) {this.orderPrice = orderPrice;}public LocalDateTime getOrderCreateTime() {return orderCreateTime;}public void setOrderCreateTime(LocalDateTime orderCreateTime) {this.orderCreateTime = orderCreateTime;}public LocalDateTime getOrderUpdateTime() {return orderUpdateTime;}public void setOrderUpdateTime(LocalDateTime orderUpdateTime) {this.orderUpdateTime = orderUpdateTime;}public Integer getOrderStatus() {return orderStatus;}public void setOrderStatus(Integer orderStatus) {this.orderStatus = orderStatus;}@Overridepublic String toString() {return "Myorder{" +"orderId=" + orderId +", orderNumber=" + orderNumber +", customerId=" + customerId +", proName=" + proName +", proId=" + proId +", proPrice=" + proPrice +", proMainImg=" + proMainImg +", proBuyCount=" + proBuyCount +", orderPrice=" + orderPrice +", orderCreateTime=" + orderCreateTime +", orderUpdateTime=" + orderUpdateTime +", orderStatus=" + orderStatus +"}";}
}

MyorderMapper.java


package com.example.mapper;import com.example.entity.Myorder;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>*  Mapper 接口* </p>** @author dd* @since 2024-05-06*/
public interface MyorderMapper extends BaseMapper<Myorder> {}

MyorderServiceImpl.java


package com.example.service.impl;import com.example.controller.ProductClient;
import com.example.entity.Myorder;
import com.example.mapper.MyorderMapper;
import com.example.service.IMyorderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.time.LocalDateTime;
import java.util.UUID;/*** <p>*  服务实现类* </p>** @author dd* @since 2024-05-06*/
@Service
public class MyorderServiceImpl  implements IMyorderService {@Autowiredprivate MyorderMapper  myorderMapper;@Autowiredprivate ProductClient productClient;@GlobalTransactional(name = "saveOrder",rollbackFor = Exception.class)public boolean save(Myorder myorder){String proStr = productClient.getProductById(myorder.getProId());System.out.println("订单中的商品是:" + proStr);myorder.setOrderNumber(UUID.randomUUID().toString().replace("-",""));myorder.setOrderCreateTime(LocalDateTime.now());myorder.setOrderStatus(1);int orderRows =  myorderMapper.insert(myorder);if(orderRows >0){//int a = 10/0; //(1)没有异常,下订单,减库存  (2)有异常,则下订单回滚productClient.decrCount(myorder.getProId(),myorder.getProBuyCount()); // 减库存}System.out.println("MyorderServiceImpl 添加订单成功,并减库存了");return  true;}}

IMyorderService.java

package com.example.service;import com.example.entity.Myorder;
import com.baomidou.mybatisplus.extension.service.IService;/*** <p>*  服务类* </p>** @author dd* @since 2024-05-06*/
public interface IMyorderService  {public boolean save(Myorder myorder);
}

OrderServerApplication.java


package com.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@MapperScan("com.example.mapper")
public class OrderServerApplication {public static void main(String[] args) {SpringApplication.run(OrderServerApplication.class, args);}}

ServletInitializer.java


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(OrderServerApplication.class);}}

bootstrap.yaml


spring:application:name: orderServerprofiles:active: devcloud:nacos:config:server-addr: localhost:8848file-extension: yaml

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.example</groupId><artifactId>springCloudAlibaba</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.example</groupId><artifactId>orderServer</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>orderServer</name><description>orderServer</description><properties><java.version>1.8</java.version></properties><dependencies><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-all</artifactId><version>1.5.2</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generate --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><!--        内置了 LoadBalancer 负载均衡器--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-loadbalancer</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><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-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

MyorderMapper.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.MyorderMapper"></mapper>

productServer

ProductController.java


package com.example.controller;import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.entity.Product;
import com.example.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("product")
public class ProductController {@Value("${server.port}")private Integer serverPort;@Autowiredprivate IProductService productService;// 减库存@GetMapping("decrCount/{proId}/{decrCount}")public String decrCount(@PathVariable("proId") Integer proId,@PathVariable("decrCount") Integer decrCount ){boolean result =   productService.decrCount(proId,decrCount);if(result)return "Product  decrCount successfully";return "Product  decrCount fail";}@GetMapping("/{proId}")@SentinelResource(value = "getById",blockHandler ="fun1",fallback = "fun2")public String getById(@PathVariable("proId") Integer proId){final Product product = productService.getById(proId);System.out.println("商品服务" + serverPort + "正在查询商品:" + proId);
//            int a = 10/0;return product.toString() ;}/*** 违背流控规则,blockHandler*  product/{proId}*  有流控规则,QPS <=1*  若超过流量阈值,blockHandler*/public String fun1(@PathVariable("proId") Integer proId,  BlockException exception) {return "商品查询请求QPS >1,超过流量阈值";}/**业务有异常,fallback*/public String fun2(@PathVariable("proId") Integer proId,  Throwable e) {Product product = new Product();product.setProductId(proId);product.setProductName("保温杯");return "[fallback]商品查询的信息是:" + product;}}

Product.java


package com.example.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;/*** <p>* * </p>** @author dd* @since 2024-05-06*/
public class Product implements Serializable {private static final long serialVersionUID = 1L;@TableId(value = "product_id", type = IdType.AUTO)private Integer productId;private String productName;private BigDecimal productPrice;private String productImg;private Integer productCount;private LocalDateTime createTime;private LocalDateTime updateTime;public Integer getProductId() {return productId;}public void setProductId(Integer productId) {this.productId = productId;}public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}public BigDecimal getProductPrice() {return productPrice;}public void setProductPrice(BigDecimal productPrice) {this.productPrice = productPrice;}public String getProductImg() {return productImg;}public void setProductImg(String productImg) {this.productImg = productImg;}public Integer getProductCount() {return productCount;}public void setProductCount(Integer productCount) {this.productCount = productCount;}public LocalDateTime getCreateTime() {return createTime;}public void setCreateTime(LocalDateTime createTime) {this.createTime = createTime;}public LocalDateTime getUpdateTime() {return updateTime;}public void setUpdateTime(LocalDateTime updateTime) {this.updateTime = updateTime;}@Overridepublic String toString() {return "Product{" +"productId=" + productId +", productName=" + productName +", productPrice=" + productPrice +", productImg=" + productImg +", productCount=" + productCount +", createTime=" + createTime +", updateTime=" + updateTime +"}";}
}

ProductMapper.java


package com.example.mapper;import com.example.entity.Product;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>*  Mapper 接口* </p>** @author dd* @since 2024-05-06*/
public interface ProductMapper extends BaseMapper<Product> {}

ProductServiceImpl.java


package com.example.service.impl;import com.example.entity.Product;
import com.example.mapper.ProductMapper;
import com.example.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.time.LocalDateTime;/*** <p>*  服务实现类* </p>** @author dd* @since 2024-05-06*/
@Service
public class ProductServiceImpl  implements IProductService {@Autowiredprivate ProductMapper productMapper;@Overridepublic Product getById(Integer proId) {return productMapper.selectById(proId);}// 减库存@Overridepublic boolean decrCount(Integer proId, Integer decrCount) {Product product =  productMapper.selectById(proId);Integer newProductCount = product.getProductCount() - decrCount;product.setProductCount(newProductCount);product.setUpdateTime(LocalDateTime.now());int rows =  productMapper.updateById(product );System.out.println("修改商品库存:" + (rows >0));return rows>0;}}

IProductService.java


package com.example.service;import com.example.entity.Product;
import com.baomidou.mybatisplus.extension.service.IService;/*** <p>*  服务类* </p>** @author dd* @since 2024-05-06*/
public interface IProductService  {public Product getById(Integer proId);//修改商品库存(减库存)public boolean decrCount(Integer proId,Integer decrCount);}

ProductServerApplication.java


package com.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.example.mapper")
public class ProductServerApplication {public static void main(String[] args) {SpringApplication.run(ProductServerApplication.class, args);}}

ServletInitializer.java


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(ProductServerApplication.class);}}

ProductMapper.xml


<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.ProductMapper"></mapper>

bootstrap.yaml


spring:application:name: productServerprofiles:active: devcloud:nacos:config:file-extension: yamlserver-addr: localhost:8848

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.example</groupId><artifactId>springCloudAlibaba</artifactId><version>0.0.1-SNAPSHOT</version></parent><groupId>com.example</groupId><artifactId>productServer</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>productServer</name><description>productServer</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!--        =====================mybatis =============================--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generate --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><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-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.6</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>springCloudAlibaba</artifactId><version>0.0.1-SNAPSHOT</version><name>springCloudAlibaba</name><description>springCloudAlibaba</description><modules><module>orderServer</module><module>productServer</module><module>gatewayServer</module><module>nacosConfigServer</module></modules><packaging>pom</packaging><properties><java.version>1.8</java.version><spring-cloud.version>2021.0.4</spring-cloud.version><spring-cloud-alibaba.version>2021.0.4.0</spring-cloud-alibaba.version></properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${spring-cloud-alibaba.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/7860.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

快速修改禅道系统的管理员密码

目录 通过 web 登录页面忘记密码&#xff08;推荐&#xff09;通过数据库&#xff0c;修改 zt_user 表 通过 web 登录页面忘记密码&#xff08;推荐&#xff09; 只能修改管理员密码。 打开禅道地址&#xff0c;点击忘记密码会显示下面的页面&#xff1a; 根据提示在服务器的相…

LeetCode 字符串专题——KMP算法_28. 找出字符串中第一个匹配项的下标

字符串专题——KMP算法 KMP算法例题 KMP算法 待更新 例题 https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/ class Solution {vector<int> next;void getNext(string s){int j-1;next[0]-1;int lens.size();for(int i…

【busybox记录】【shell指令】shuf

目录 内容来源&#xff1a; 【GUN】【shuf】指令介绍 【busybox】【shuf】指令介绍 【linux】【shuf】指令介绍 使用示例&#xff1a; 打乱内容 - 默认输出 打乱内容 - 最多输出n行 打乱内容 - 将输出写入文件 打乱内容 - 重复输出 打乱内容 - 打乱本条指令的参数 打…

并发控制互斥笔记

整理总结自蒋炎岩老师的b站课程&#xff0c;https://jyywiki.cn/OS/2022/index.html 多处理器系统中数据的一致性和互斥访问 所有的CPU的一级缓存都是连着的&#xff0c;如果是多个CPU的话&#xff0c;用在内存中放置标志位&#xff0c;来保证对当前内容的原子性读取&#xff0…

minio getPresignedObjectUrl(GetPresignedObjectUrlArgs args)如何使用

在MinIO Java SDK中&#xff0c;getPresignedObjectUrl 方法现在接受一个 GetPresignedObjectUrlArgs 对象作为参数&#xff0c;这个对象允许你更加灵活地配置生成预签名URL的行为。以下是使用这个方法的一个示例&#xff1a; 首先&#xff0c;确保你已经添加了MinIO Java SDK…

第六代移动通信介绍、无线网络类型、白皮书

关于6G 即第六代移动通信的介绍&#xff0c; 图解通信原理与案例分析-30&#xff1a;6G-天地互联、陆海空一体、全空间覆盖的超宽带移动通信系统_6g原理-CSDN博客文章浏览阅读1.7w次&#xff0c;点赞34次&#xff0c;收藏165次。6G 即第六代移动通信&#xff0c;6G 将在5G 的基…

经常发文章的你是否想过定时发布是咋实现的?

前言 可乐他们团队最近在做一个文章社区平台,由于人手不够,前后端都是由前端同学来写。后端使用 nest 来实现。 某一天周五下午,可乐正在快乐摸鱼,想到周末即将来临,十分开心。然而,产品突然找到了他,说道:可乐,我们要做一个文章定时发布功能。 现在我先为你解释一…

「代码与养生」 :当下程序员的养生指南

前言 众所周知&#xff0c;程序员是死的比较快的一类人。因为天天加班、睡眠不足、久坐不动、长时间面对电子屏幕辐射、长时间高强度用脑等不好避免的问题。因此&#xff0c;要想活的时间长一点&#xff0c;就要多了解一些养生之道 下面&#xff0c;根据个人看的一些博客、书…

Vue2和Vue3的优化

在Vue.js 2中&#xff0c;你可以使用异步组件来延迟加载组件&#xff0c;以提高应用的性能。以下是使用异步组件的步骤&#xff1a; 创建一个异步组件。你可以使用Vue.component()函数来定义一个异步组件&#xff0c;例如&#xff1a; Vue.component(AsyncComponent, functio…

LinkedList常考面试题

LinkedList是Java集合框架中的一个重要部分&#xff0c;它是一种线性数据结构&#xff0c;不同于ArrayList基于数组实现&#xff0c;LinkedList是基于双向链表实现的。这使得它在插入、删除操作上具有较高的效率&#xff0c;但随机访问元素时效率较低。以下是一些关于LinkedLis…

getline的使用条件以及限制条件

getline函数在C中有两种主要的形式&#xff0c;分别是C标准库提供的用于读取文本行的std::getline函数&#xff0c;以及POSIX兼容系统&#xff08;如GNU C&#xff09;提供的C风格的getline函数。 1. C标准库中的std::getline函数 #include <iostream> #include <st…

Android中正确启动一个页面的方法

1.通过要启动的Activity的类名直接启动一个Activity&#xff0c;假设要启动的Activity的类名为TestActivity。 Intent intentnew Intent();intent.setClass(this,TestActivity.class);context.startActivity(intent); 2. 使用Action、Category等限制参数隐式启动Activity。 I…

Vue进阶(贰零捌)如何实现浏览器地址栏URL参数隐藏

文章目录 一、前言二、动态路由三、Params 参数四、在 URL 中使用加密参数五、拓展阅读 一、前言 在应用 vue.js 开发前端项目时&#xff0c;浏览器中url 地址栏参数的处理是一个很基础但却很重要的问题。在很多情况下&#xff0c;我们需要从 url 中获取参数&#xff0c;比如从…

表空间的创建

目录 表空间创建的语法 表空间创建的例子 创建一个永久性表空间&#xff0c;设置表空间初始大小为100MB&#xff0c;自动扩展为 100MB&#xff0c;无最大大小限制&#xff0c;并且该表空间为在线状态&#xff0c;产生日志 创建一个永久性表空间&#xff0c;通过本地化管理方…

面向新手在无人机竞速场景下的飞行辅助系统——浙大 FAST-Lab 高飞团队 ICRA 论文三项 Best Paper 入围

恭喜浙江大学 FAST-Lab 钟宇航同学的论文 A Trajectory-based Flight Assistive System for Novice Pilots in Drone Racing Scenario 顺利发表 ICRA 2024&#xff0c;并同时入选三项 Finalist&#xff1a; the IEEE ICRA Best Conference Paper Awardthe IEEE ICRA Best Pape…

深入理解Java虚拟机(JVM)

引言&#xff1a; Java虚拟机&#xff08;JVM&#xff09;是Java平台的核心组件&#xff0c;它负责将Java字节码转换成平台特定的机器指令&#xff0c;并在相应的硬件和操作系统上执行。JVM的引入使得Java语言具有“一次编写&#xff0c;到处运行”的跨平台特性。本文将深入探…

Android Framework中PackageManagerService的深度剖析

摘要 Android操作系统的核心服务之一——PackageManagerService(PMS)&#xff0c;扮演着至关重要的角色&#xff0c;负责维护系统中所有应用程序的生命周期管理。本文旨在全面探讨PMS的功能特性、工作流程、实际应用场景&#xff0c;并对其进行优劣分析&#xff0c;以期为开发者…

ICC2:optimize_routability

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧? 拾陆楼知识星球入口 在postroute阶段,一些pin access引起的绕线问题,通常以end of line和short/spacing的形式扎堆出现,总量兴许不多,但是反复绕线仍难解决,返回preplace去设置keepout margin或placement label又得…

绘画作品3d数字云展厅提升大众的艺术鉴赏和欣赏能力

3D虚拟展厅作为未来艺术的展示途径&#xff0c;正逐渐成为文化创意产业蓬勃发展的重要引擎。这一创新形式不仅打破了传统艺术展览的局限性&#xff0c;更以其独特的魅力吸引着全球观众的目光。 3D虚拟艺术品展厅以其独特的魅力&#xff0c;助力提升大众的艺术鉴赏和欣赏能力。观…

什么是多模态大模型,有了大模型,为什么还要多模态大模型?

随着人工智能技术的愈演愈烈&#xff0c;其技术可以说是日新月异&#xff0c;每隔一段时间就会有新的技术和理念被创造出来&#xff1b;而多模态大模型也是其中之一。 什么是多模态 想弄明白什么是多模态大模型&#xff0c;那么首先就要弄明白什么是多模态。 简单来说&#x…