006 springCloudAlibaba seata

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: 7091

spring:
  application:
    name: seataServer

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${user.home}/logs/seata
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

console:
  user:
    username: seata
    password: seata

seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: nacos
    nacos:
      namespace:
      group: DEFAULTGROUP
      data-id: seataServer.properties
      username: 
      password:
      server-addr: http://127.0.0.1:8848
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos



  store:
    # support: file 、 db 、 redis
    mode: db
#  server:
#    service-port: 8091 #If not configured, the default is '${server.port} + 1000'
  security:
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
    tokenValidityInMilliseconds: 1800000
    ignore:
      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: 9001


spring:
  application:
    name: orderServer
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cloud_order_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  cloud:
    nacos:
      server-addr: localhost:8848 # ?????URL
    sentinel:
      transport:
        dashboard: localhost:8080 #??Sentinel dashboard??
        port: 8719

management:
  endpoints:
    web:
      exposure:
        include: '*'

feign:
  sentinel:
    enabled: true # ??Sentinel?Feign???
seata:
  tx-service-group: fsp_tx_group
  registry:
    type: nacos
    nacos:
      server-addr: localhost:8848
  service:
    vgroup-mapping:
      fsp_tx_group: default

Data ID:productServer-dev.yaml

Group:DEFAULT_GROUP

server:
  port: 7001

spring:
  application:
    name: productServer
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cloud_product_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  cloud:
    nacos:
      server-addr: localhost:8848  # ???? nacos ???
    sentinel:
      transport:
        dashboard: localhost:8080 #??Sentinel dashboard??
        port: 8719

management:
  endpoints:
    web:
      exposure:
        include: '*'

feign:
  sentinel:
    enabled: true # ??Sentinel?Feign???

DataID:gatewayServer-dev.yaml

Group:DEFAULT_GROUP


server:
  port: 9090
spring:
  application:
    name: gatewayServer
  cloud:
    nacos:  # nacos url
      discovery:
        server-addr: localhost:8848
    sentinel: #sentinel url
      transport:
        dashboard: localhost:8080
    gateway:   # gateway
      discovery:
        locator:
          enabled: true #??gateway?nacos???????
      routes:
        - id: order_route
          uri: lb://orderServer # ??orderServer???????????Nacos???
          predicates:
            - Path=/order/**
            - Method=GET,POST
            - Before=2025-07-09T17:42:47.789-07:00[Asia/Shanghai]


        - id: product_route
          uri: 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=default

store.mode=db

store.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 {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(GatewayServerApplication.class);
    }

}


bootstrap.yaml



spring:
  application:
    name: gatewayServer
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-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-value
    private int serverPort;

    @Autowired
    private IMyorderService myorderService;

    // 下订单
    @PostMapping
    public 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;
    }

    @Override
    public 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 {

    @Autowired
    private MyorderMapper  myorderMapper;

    @Autowired
    private 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 {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(OrderServerApplication.class);
    }

}


bootstrap.yaml


spring:
  application:
    name: orderServer
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-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;
    @Autowired
    private 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;
    }

    @Override
    public 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 {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product getById(Integer proId) {
        return productMapper.selectById(proId);
    }

    // 减库存
    @Override
    public 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 {

    @Override
    protected 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: productServer
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        file-extension: yaml
        server-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>



相关推荐

  1. 006 RabbitMQ

    2024-05-11 05:28:04       37 阅读
  2. 006 springCloudAlibaba seata

    2024-05-11 05:28:04       25 阅读
  3. 大数据004-hadoop002-数据

    2024-05-11 05:28:04       30 阅读
  4. Python语言例题集(006

    2024-05-11 05:28:04       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-11 05:28:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-11 05:28:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-11 05:28:04       87 阅读
  4. Python语言-面向对象

    2024-05-11 05:28:04       97 阅读

热门阅读

  1. 2、TS中的基础讲解

    2024-05-11 05:28:04       29 阅读
  2. Transformer优化加速--xformers

    2024-05-11 05:28:04       33 阅读
  3. tengine-docker镜像制作

    2024-05-11 05:28:04       33 阅读
  4. docker部署go项目

    2024-05-11 05:28:04       30 阅读
  5. mysql的事务隔离级别和JDBC

    2024-05-11 05:28:04       27 阅读
  6. 公网,专用,共享,及独立IP地址

    2024-05-11 05:28:04       30 阅读