Jmeter学习笔记

SpringCloud Alibaba学习笔记

1、项目搭建

版本依赖关系:https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E

Jmeter学习笔记_第1张图片
Jmeter学习笔记_第2张图片

1.1、搭建父工程

spring-initializr构建项目
在这里插入图片描述
Jmeter学习笔记_第3张图片

清理父工程中不必要的文件/文件夹
Jmeter学习笔记_第4张图片

修改pom.xml文件


<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.0modelVersion>

    
    
    
    
    
    
    

    
    <groupId>com.examplegroupId>
    <artifactId>springcloud-demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>springcloud-demoname>
    <description>springcloud-demodescription>

    
    <properties>
        <java.version>1.8java.version>
        <spring-boot.revision>2.6.3spring-boot.revision>
        <spring-cloud.version>2021.0.1spring-cloud.version>
        <spring-cloud-alibaba.version>2021.0.1.0spring-cloud-alibaba.version>
    properties>

    
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-parentartifactId>
                <version>${spring-boot.revision}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                <version>${spring-cloud-alibaba.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

project>

1.2、子项目

1、account

创建子项目
在这里插入图片描述

子项目添加启动类和配置文件
Jmeter学习笔记_第5张图片

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccountApplication {
    public static void main(String[] args) {
        SpringApplication.run(AccountApplication.class, args);
    }
}
server:
  port: 10010

子项目打包方式修改
Jmeter学习笔记_第6张图片


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2、blog

创建子项目
Jmeter学习笔记_第7张图片

子项目添加启动类和配置文件
Jmeter学习笔记_第8张图片

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}
server:
  port: 10020

子项目打包方式修改
Jmeter学习笔记_第9张图片


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2、Nacos

这里采用docker的方式部署

如果直接在主机上部署可以在https://github.com/alibaba/nacos/releases找需要的版本

2.1、部署Mysql

1、Mysql

docker run -d \
    -p 3306:3306 \
    --name mysql \
    -v mysql-data:/var/lib/mysql \
    -e MYSQL_ROOT_PASSWORD=123456 \
    --privileged=true \
    --restart=always \
    mysql:5.7.42

2、初始化

 /*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info   */
/******************************************/
CREATE DATABASE nacos;
USE nacos;
CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_aggr   */
/******************************************/
CREATE TABLE `config_info_aggr` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
  `content` longtext NOT NULL COMMENT '内容',
  `gmt_modified` datetime NOT NULL COMMENT '修改时间',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_beta   */
/******************************************/
CREATE TABLE `config_info_beta` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_tag   */
/******************************************/
CREATE TABLE `config_info_tag` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_tags_relation   */
/******************************************/
CREATE TABLE `config_tags_relation` (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = group_capacity   */
/******************************************/
CREATE TABLE `group_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = his_config_info   */
/******************************************/
CREATE TABLE `his_config_info` (
  `id` bigint(64) unsigned NOT NULL,
  `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) NOT NULL,
  `group_id` varchar(128) NOT NULL,
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL,
  `md5` varchar(32) DEFAULT NULL,
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text,
  `src_ip` varchar(50) DEFAULT NULL,
  `op_type` char(10) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = tenant_capacity   */
/******************************************/
CREATE TABLE `tenant_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';


CREATE TABLE `tenant_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) default '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) default '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
    `username` varchar(50) NOT NULL PRIMARY KEY,
    `password` varchar(500) NOT NULL,
    `enabled` boolean NOT NULL
);

CREATE TABLE `roles` (
    `username` varchar(50) NOT NULL,
    `role` varchar(50) NOT NULL,
    UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` varchar(50) NOT NULL,
    `resource` varchar(255) NOT NULL,
    `action` varchar(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');

2.2、部署Nacos

docker run -itd \
    -e MODE=standalone \
    -e SPRING_DATASOURCE_PLATFORM=mysql \
    -e MYSQL_SERVICE_HOST=150.158.24.200 \
    -e MYSQL_SERVICE_PORT=3306 \
    -e MYSQL_SERVICE_DB_NAME=nacos \
    -e MYSQL_SERVICE_USER=root \
    -e MYSQL_SERVICE_PASSWORD=123456 \
    -p 8848:8848 \
    --name nacos \
    --restart=always \
    nacos/nacos-server:1.4.2

2.3、可视化界面

可视化界面:http://150.158.24.200:8848/nacos/

初始账号密码为:nacos/nacos
Jmeter学习笔记_第10张图片
Jmeter学习笔记_第11张图片

2.4、项目配置注册中心

2.5、pom.xml添加nacos

均在子项目中配置

1、account


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2、blog


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2.6、application.yaml添加nacos

1、account

server:
  port: 10010
spring:
  # 应用名称
  application:
    name: account
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    loadbalancer:
      cache:
        enabled: false

2、blog

server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    loadbalancer:
      cache:
        enabled: false

2.7、服务调用

可在面板里面打开service面板(有时候无法显示出来springboot服务面板,可以在services->±>run configuration->springboot)
在这里插入图片描述

1、account

服务提供者

controller

// account/src/main/java/com/example/controller/HelloController.java
@RestController
public class HelloController {

    @Value("${server.port}")
    String port;
    
    @RequestMapping("/account")
    public String hello() {
        return "Hello xumeng03-"+port;
    }
}

2、blog

服务调用者

Configuration

// blog/src/main/java/com/example/CustomConfiguration.java
@Configuration
public class CustomConfiguration {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }
}

controller

// blog/src/main/java/com/example/controller/HelloController.java
@RestController
public class HelloController {

    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/blog")
    public String hello() {
        return restTemplate.getForObject("http://account/account", String.class);
    }
}

在这里插入图片描述

2.8、应用启动多实例

在service面板里面选中要复制的应用,右键选择Copy Configuration
Jmeter学习笔记_第12张图片
修改服务名称和端口(Environment variables如果没有的话,可以在Modify options选项里面勾选上)
Jmeter学习笔记_第13张图片

3、Openfeign

3.1、pom.xml添加openfeign

1、account


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2、blog


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

3.2、服务调用

1、account

// account/src/main/java/com/example/controller/HelloController.java
@RestController
public class HelloController {

    @Value("${server.port}")
    String port;

    @RequestMapping("/account/{name}")
    public String hello(@PathVariable("name") String name) {
        return "Hello " + name + " " + port;
    }
}

2、blog

// blog/src/main/java/com/example/openfeign/AccountOpenfeign.java
// name指定服务名,path指定Controller的RequestMapping,configuration用于指定特殊的配置
@FeignClient(name = "account")
public interface AccountOpenfeign {
    @RequestMapping("/account/{name}")
    String hello(@PathVariable("name") String name);
}
// blog/src/main/java/com/example/controller/HelloController.java
@RestController
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    AccountOpenfeign accountOpenfeign;

    @RequestMapping("/blog")
    public String hello() {
        return accountOpenfeign.hello("xumeng03");
    }
}

3.3、修改启动类

// blog/src/main/java/com/example/BlogApplication.java
@SpringBootApplication
// 添加启用FeignClients
@EnableFeignClients
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

3.4、Openfeign日志级别

1、配置类

// blog/src/main/java/com/example/config/CustomConfiguration.java
@Configuration
public class CustomConfiguration {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }
    
    @Bean
    public Logger.Level openFeignLoggerLevel(){
        // 输出完整日志
        return Logger.Level.FULL;
    }
}

因为springboot的默认日志级别info大于openFeign的debug,所以要再配置文件中单独配置下

# blog/src/main/resources/application.yaml
server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    loadbalancer:
      cache:
        enabled: false
logging:
  level:
    # 路径为FeignClient的路径
    com.example.openfeign.AccountOpenfeign: debug

2、配置文件

# blog/src/main/resources/application.yaml
server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    loadbalancer:
      cache:
        enabled: false
logging:
  level:
    # 路径为FeignClient的路径
    com.example.openfeign.AccountOpenfeign: debug
feign:
  client:
    config:
      account:
        logger-level: BASIC

3.5、Openfeign超时时间

1、配置类

// blog/src/main/java/com/example/config/CustomConfiguration.java
@Configuration
public class CustomConfiguration {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }

    @Bean
    public Logger.Level openFeignLoggerLevel(){
        // 输出完整日志
        return Logger.Level.FULL;
    }

    @Bean
    public Request.Options openFeignRequestOption(){
        // connectTimeoutMillis连接超时时间(默认2s),readTimeoutMillis请求处理超时时间(默认5s)
        return new Request.Options(3000,10000);
    }
}

2、配置文件

# blog/src/main/resources/application.yaml
server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    loadbalancer:
      cache:
        enabled: false
logging:
  level:
    # 路径为FeignClient的路径
    com.example.openfeign.AccountOpenfeign: debug
# openfeign配置
feign:
  client:
    config:
      account:
        # 日志级别
        logger-level: BASIC
        # 连接超时时间,默认2s
        connect-timeout: 3000
        # 请求处理超时时间,默认5s
        readTimeout: 10000

4、配置中心

配置文档:https://github.com/alibaba/spring-cloud-alibaba/wiki/Nacos-config

http://150.158.24.200:8848/nacos/#/configurationManagement

4.1、添加配置

Jmeter学习笔记_第14张图片

4.2、添加依赖

1、account


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2、blog


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

4.3、bootstrap.properties

必须使用bootstrap.properties/bootstrap.yaml指定nacos server的地址

1、account

# account/src/main/resources/bootstrap.yaml
spring:
  application:
    # 需和配置文件的DataId一致(如果不一致需要使用extension-configs或shared-configs,extension-configs优先级更高)
    name: account
  cloud:
    # nacos配置
    nacos:
      config:
        # nacos地址
        server-addr: 150.158.24.200:8848
        # 配置文件后缀(只针对默认配置文件和profile文件)
        file-extension: yaml

2、blog

# account/src/main/resources/bootstrap.yaml
spring:
  application:
    # 需和配置文件的DataId一致(如果不一致需要使用extension-configs或shared-configs,extension-configs优先级更高)
    name: account
  cloud:
    # nacos配置
    nacos:
      config:
        # nacos地址
        server-addr: 150.158.24.200:8848
        # 配置文件后缀(只针对默认配置文件和profile文件)
        file-extension: yaml

4.4、修改controller

1、account

// account/src/main/java/com/example/controller/HelloController.java
@RestController
// 一定要加,否则@Value无法获取动态更新的值
@RefreshScope
public class HelloController {

    @Value("${server.port}")
    String port;

    @Value("${user.name}")
    String userName;

    @Value("${user.age}")
    String age;

    @RequestMapping("/account/{name}")
    public String hello(@PathVariable("name") String name) {
        System.out.println(name);
        return "Hello " + userName + " " + age;
    }
}

可以看到此时获取到了文件内容并且会随着配置文件更新而更新
Jmeter学习笔记_第15张图片

Jmeter学习笔记_第16张图片

2、blog

// blog/src/main/java/com/example/controller/HelloController.java
@RestController
@RefreshScope
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    AccountOpenfeign accountOpenfeign;

    @Value("${environment.name}")
    String env;

    @RequestMapping("/blog")
    public String hello() {
        return accountOpenfeign.hello("xumeng03") + " " + env;
    }
}

blog为了演示profiles效果,结果如下小节所示

4.5、修改配置文件

1、account

保持不变

2、blog

server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  # 设置激活配置文件
  profiles:
    active: dev
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    loadbalancer:
      cache:
        enabled: false
logging:
  level:
    # 路径为FeignClient的路径
    com.example.openfeign.AccountOpenfeign: debug

可以看到对应的内容被输出出来了(并且若指定激活的配置文件没有对应的内容会去默认的配置文件中寻到对应的内容进行填充)
Jmeter学习笔记_第17张图片

5、Sentinal

5.1、下载运行

要根据springcloud-alibaba版本下载对应的版本:https://github.com/alibaba/Sentinel/releases/download/1.8.3/sentinel-dashboard-1.8.3.jar

java -jar -Dserver.port=8858 -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboard.auth.password=sentinel sentinel-dashboard-1.8.3.jar

5.2、添加依赖

1、account


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.examplegroupId>
            <artifactId>commonartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2、blog


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.examplegroupId>
            <artifactId>commonartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

5.3、修改配置文件

1、account

server:
  port: 10010
spring:
  # 应用名称
  application:
    name: account
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
        # sentinel配置
    sentinel:
      transport:
        dashboard: localhost:8858
    loadbalancer:
      cache:
        enabled: false

2、blog

server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  # 设置激活配置文件
  profiles:
    active: dev
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    # sentinel配置
    sentinel:
      transport:
        dashboard: localhost:8858
    loadbalancer:
      cache:
        enabled: false
logging:
  level:
    # 路径为FeignClient的路径
    com.example.openfeign.AccountOpenfeign: debug

5.4、修改controller

1、account

// account/src/main/java/com/example/controller/HelloController.java
@RestController
@RefreshScope
public class HelloController {

    @Value("${server.port}")
    String port;

    @Value("${user.name}")
    String userName;

    @Value("${user.age}")
    String age;

    @RequestMapping("/account/{name}")
    @SentinelResource
    public String hello(@PathVariable("name") String name) {
        System.out.println(name);
        return "Hello " + userName + " " + age;
    }

    @RequestMapping("/account/common")
    @SentinelResource
    public String common() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }
}

2、blog

// blog/src/main/java/com/example/controller/HelloController.java
@RestController
@RefreshScope
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    AccountOpenfeign accountOpenfeign;

    @Value("${environment.name}")
    String env;

    @RequestMapping("/blog")
    @SentinelResource
    public String hello() {
        return accountOpenfeign.hello("xumeng03") + " " + env;
    }

    @RequestMapping("/blog/common")
    @SentinelResource
    public String common() {
        return JSON.toJSONString(new Blog("title", "content"));
    }
}

5.5、服务面板

访问几次服务接口,就可以在sentinel dashboard里面看到服务
Jmeter学习笔记_第18张图片

Jmeter学习笔记_第19张图片

5.6、限流(QPS)

1、account

配置服务降级

// account/src/main/java/com/example/controller/HelloController.java
@RestController
@RefreshScope
public class HelloController {

    @Value("${server.port}")
    String port;

    @Value("${user.name}")
    String userName;

    @Value("${user.age}")
    String age;

    @RequestMapping("/account/{name}")
    @SentinelResource(value = "account", blockHandler = "blockHandler")
    public String hello(@PathVariable("name") String name) {
        System.out.println(name);
        return "Hello " + userName + " " + age;
    }

    @RequestMapping("/account/common")
    @SentinelResource(value = "account-common", blockHandler = "blockHandler")
    public String common() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }

    public String blockHandler(BlockException blockException) {
        return "流控";
    }
}

添加流控
Jmeter学习笔记_第20张图片

Jmeter学习笔记_第21张图片

多刷新几次
在这里插入图片描述

5.7、限流(并发线程)

1、blog

配置服务降级

// blog/src/main/java/com/example/controller/HelloController.java
@RestController
@RefreshScope
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    AccountOpenfeign accountOpenfeign;

    @Value("${environment.name}")
    String env;

    @RequestMapping("/blog")
    @SentinelResource(value = "blog", blockHandler = "blockHandler")
    public String hello() {
        return accountOpenfeign.hello("xumeng03") + " " + env;
    }

    @RequestMapping("/blog/common")
    @SentinelResource(value = "blog-common", blockHandler = "blockHandler")
    public String common() throws InterruptedException {
        Thread.sleep(5000);
        return JSON.toJSONString(new Blog("title", "content"));
    }

    public String blockHandler(BlockException blockException) {
        return "流控" + blockException.toString();
    }
}

添加流控
在这里插入图片描述

Jmeter学习笔记_第22张图片

多刷新几次
Jmeter学习笔记_第23张图片

5.8、异常统一处理

1、设置统一异常处理

// blog/src/main/java/com/example/exception/BlockException.java
@Configuration
public class BlockException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, com.alibaba.csp.sentinel.slots.block.BlockException e) throws Exception {
        String msg = "";
        if (e instanceof FlowException) {
            msg = "接口限流";
        } else if (e instanceof DegradeException) {
            msg = "服务降级";
        } else if (e instanceof ParamFlowException) {
            msg = "热点参数限流";
        } else if (e instanceof SystemBlockException) {
            msg = "触发系统保护规则";
        } else if (e instanceof AuthorityException) {
            msg = "授权规则不通过";
        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("content-type", "text/html; charset=UTF-8");
        httpServletResponse.getWriter().write(msg);
    }
}

2、设置流控

Jmeter学习笔记_第24张图片

3、测试

Jmeter学习笔记_第25张图片

5.9、限流(关联)

当接口具有资源竞争的时候,接口便有了关联,此时若重要接口访问频率变高,需要限制不重要的接口的访问

1、添加流控

Jmeter学习笔记_第26张图片

Jmeter学习笔记_第27张图片

2、Jmeter访问

线程组配置
Jmeter学习笔记_第28张图片

取样器配置
Jmeter学习笔记_第29张图片

3、测试

Jmeter学习笔记_第30张图片

Jmeter学习笔记_第31张图片

5.10、限流(链路)

1、修改配置文件

server:
  port: 10010
spring:
  # 应用名称
  application:
    name: account
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
        # sentinel配置
    sentinel:
      transport:
        dashboard: localhost:8858
      # 添加链路展开
      web-context-unify: false
    loadbalancer:
      cache:
        enabled: false

2、修改service

@Service
public class Blogservice {
    @SentinelResource(value = "new-account")
    public String newAccount() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }
}

3、修改controller

@RestController
public class LinkController {
    @Autowired
    Blogservice blogservice;
    
    @RequestMapping("/blog/link1")
    public String link1() {
        return blogservice.newAccount();
    }

    @RequestMapping("/blog/link2")
    public String link2() {
        return blogservice.newAccount();
    }
}

4、修改流控

Jmeter学习笔记_第32张图片

Jmeter学习笔记_第33张图片

5、测试

在这里插入图片描述

5.11、熔断(慢调用)

1、controller

@RestController
public class BlowController {
    @RequestMapping("/blog/blow")
    public String blow() throws InterruptedException {
        Thread.sleep(2000);
        return "blow";
    }
}

2、修改熔断

Jmeter学习笔记_第34张图片

Jmeter学习笔记_第35张图片

3、测试

Jmeter学习笔记_第36张图片

等待一分钟,第一次访问正常,但因为超时,随后再次进入熔断

5.12、熔断(异常)

1、controller

@RestController
public class BlowController {
    @RequestMapping("/blog/blow")
    public String blow() throws InterruptedException {
        Thread.sleep(2000);
        return "blow";
    }

    @RequestMapping("/blog/blow1")
    public String blow1() {
        throw new  RuntimeException("自定义异常");
    }
}

2、修改熔断

Jmeter学习笔记_第37张图片
Jmeter学习笔记_第38张图片

3、测试

Jmeter学习笔记_第39张图片

等待一分钟,第一次访问正常,但因为超时,随后再次进入熔断

5.13、整合openfeign

1、account

@RestController
@RefreshScope
public class HelloController {

    @Value("${server.port}")
    String port;

    @Value("${user.name}")
    String userName;

    @Value("${user.age}")
    String age;

    @RequestMapping("/account/{name}")
    @SentinelResource(value = "account", blockHandler = "blockHandler")
    public String hello(@PathVariable("name") String name) {
        return "Hello " + userName + " " + age;
    }

    @RequestMapping("/account1/{name}")
    @SentinelResource(value = "account", blockHandler = "blockHandler")
    public String hello1(@PathVariable("name") String name) {
        int a = 1 / 0;
        return "Hello " + userName + " " + age;
    }

    @RequestMapping("/account/common")
    @SentinelResource(value = "account-common", blockHandler = "blockHandler")
    public String common() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }

    public String blockHandler(BlockException blockException) {
        return "流控";
    }
}

2、blog

FeignClient

@FeignClient(name = "account", fallback = AccountOpenfeignFallback.class)
public interface AccountOpenfeign {
    @RequestMapping("/account/{name}")
    String hello(@PathVariable("name") String name);

    @RequestMapping("/account1/{name}")
    String hello1(@PathVariable("name") String name);
}

FeignClientFallback

@Component
public class AccountOpenfeignFallback implements AccountOpenfeign  {
    @Override
    @RequestMapping("/account/{name}")
    public String hello(@PathVariable("name") String name){
        return "远程服务异常,服务降级";
    }

    @Override
    @RequestMapping("/account1/{name}")
    public String hello1(@PathVariable("name") String name){
        return "远程服务异常,服务降级";
    }
}

controller

@RestController
@RefreshScope
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Qualifier("com.example.openfeign.AccountOpenfeign")
    @Autowired
    AccountOpenfeign accountOpenfeign;

    @Value("${environment.name}")
    String env;

    @RequestMapping("/blog")
    @SentinelResource(value = "blog", blockHandler = "blockHandler")
    public String hello() {
        return accountOpenfeign.hello("xumeng03") + " " + env;
    }

    @RequestMapping("/blog1")
    public String hello1() {
        System.out.println("blog1");
        return accountOpenfeign.hello1("xumeng03") + " " + env;
    }

    @RequestMapping("/blog/common")
    @SentinelResource(value = "blog-common", blockHandler = "blockHandler")
    public String common() throws InterruptedException {
        Thread.sleep(5000);
        return JSON.toJSONString(new Blog("title", "content"));
    }

    public String blockHandler(BlockException blockException) {
        return "流控" + blockException.toString();
    }
}

3、测试

Jmeter学习笔记_第40张图片

5.14、热点流控

1、设置流控

Jmeter学习笔记_第41张图片
Jmeter学习笔记_第42张图片
Jmeter学习笔记_第43张图片

2、测试

Jmeter学习笔记_第44张图片

5.15、系统保护规则

Jmeter学习笔记_第45张图片

6、Seata

6.1、下载

要根据springcloud-alibaba版本下载对应的版本:https://github.com/seata/seata/releases/download/v1.4.2/seata-server-1.4.2.zip

6.2、数据库准备

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE DATABASE seata;
USE seata;
CREATE TABLE IF NOT EXISTS `global_table`
(
    `xid`                       VARCHAR(128) NOT NULL,
    `transaction_id`            BIGINT,
    `status`                    TINYINT      NOT NULL,
    `application_id`            VARCHAR(32),
    `transaction_service_group` VARCHAR(32),
    `transaction_name`          VARCHAR(128),
    `timeout`                   INT,
    `begin_time`                BIGINT,
    `application_data`          VARCHAR(2000),
    `gmt_create`                DATETIME,
    `gmt_modified`              DATETIME,
    PRIMARY KEY (`xid`),
    KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(128),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

6.3、存储模式(DB)

seata-server-1.4.2\conf\file.conf

## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  mode = "db"
  ## rsa decryption public key
  publicKey = ""

  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    ## if using mysql to store the data, recommend add rewriteBatchedStatements=true in jdbc connection param
    url = "jdbc:mysql://150.158.24.200:3306/seata?rewriteBatchedStatements=true"
    user = "root"
    password = "123456"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }
}

6.4、整合Nacos

要根据springcloud-alibaba版本下载对应的版本:https://github.com/seata/seata/tree/1.4.2 (script\config-center\nacos)

seata-server-1.4.2\conf\registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    application = "seata-server"
    serverAddr = "150.158.24.200:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"

  nacos {
    serverAddr = "150.158.24.200:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
    dataId = "seataServer.properties"
  }
}

6.5、配置中心

script\config-center\config.txt

新增seataServer.properties

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
service.vgroupMapping.my_test_tx_group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
store.mode=db
store.publicKey=
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://150.158.24.200: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.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.sentinel.masterName=
store.redis.sentinel.sentinelHosts=
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
store.redis.queryLimit=100
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898

6.6、启动

seata-server-1.4.2\bin\seata-server.bat

6.7、配置数据库

CREATE DATABASE user;
USE user;
CREATE TABLE user.user(
    id int primary key auto_increment,
    name varchar(20),
    coin int
);
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
    `branch_id`     BIGINT       NOT NULL COMMENT 'branch transaction id',
    `xid`           VARCHAR(128) NOT NULL COMMENT 'global transaction id',
    `context`       VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
    `rollback_info` LONGBLOB     NOT NULL COMMENT 'rollback info',
    `log_status`    INT(11)      NOT NULL COMMENT '0:normal status,1:defense status',
    `log_created`   DATETIME(6)  NOT NULL COMMENT 'create datetime',
    `log_modified`  DATETIME(6)  NOT NULL COMMENT 'modify datetime',
    UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';

CREATE DATABASE blog;
USE blog;
CREATE TABLE blog.blog(
    id int primary key auto_increment,
    title varchar(100),
    coin_number int
);
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
    `branch_id`     BIGINT       NOT NULL COMMENT 'branch transaction id',
    `xid`           VARCHAR(128) NOT NULL COMMENT 'global transaction id',
    `context`       VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
    `rollback_info` LONGBLOB     NOT NULL COMMENT 'rollback info',
    `log_status`    INT(11)      NOT NULL COMMENT '0:normal status,1:defense status',
    `log_created`   DATETIME(6)  NOT NULL COMMENT 'create datetime',
    `log_modified`  DATETIME(6)  NOT NULL COMMENT 'modify datetime',
    UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';

6.8、项目添加数据库配置

1、account

添加依赖


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.examplegroupId>
            <artifactId>commonartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.8version>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int coin;
}

mapper

@Repository
public interface UserMapper {
    @Select("select * from user where id=#{id}")
    User selectUser(@Param("id") int id);

    @Update("update user set coin=#{coin} where id=#{id}")
    int updateUser(User user);
}

service

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User selectUser(int id) {
        return userMapper.selectUser(id);
    }

    public int updateUser(int id) {
        User user = userMapper.selectUser(id);
        user.setCoin(user.getCoin() - 1);
        return userMapper.updateUser(user);
    }
}

controller

@RestController
@RefreshScope
public class HelloController {

    @Value("${server.port}")
    String port;

    @Value("${user.name}")
    String userName;

    @Value("${user.age}")
    String age;

    @Autowired
    UserService userService;

    @RequestMapping("/account/{name}")
    @SentinelResource(value = "account", blockHandler = "blockHandler")
    public String hello(@PathVariable("name") String name) {
        return "Hello " + userName + " " + age;
    }

    @RequestMapping("/account1/{name}")
    public String hello1(@PathVariable("name") String name) {
        int a = 1 / 0;
        System.out.println("blog1");
        return "Hello " + userName + " " + age;
    }

    @RequestMapping("/account/common")
    @SentinelResource(value = "account-common", blockHandler = "blockHandler")
    public String common() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }

    public String blockHandler(@PathVariable("name") String name, BlockException blockException) {
        return "流控";
    }

    @RequestMapping("/account2/{id}")
    public String hello(@PathVariable("id") int id) {
        return JSON.toJSONString(userService.selectUser(id));
    }

    @RequestMapping("/account3/{id}")
    public int updateUser(@PathVariable("id") int id) {
        return userService.updateUser(id);
    }
}

修改启动类

@SpringBootApplication
@MapperScan("com.example.mapper")
public class AccountApplication {
    public static void main(String[] args) {
        SpringApplication.run(AccountApplication.class, args);
    }
}

2、blog

添加依赖


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.examplegroupId>
            <artifactId>commonartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.8version>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog1 {
    private int id;
    private String title;
    private int coin_number;
}

mapper

@Repository
public interface BlogMapper {
    @Select("select * from blog where id=#{id}")
    Blog1 selectBlog(@Param("id") int id);

    @Update("update blog set coin_number=#{coin_number} where id=#{id}")
    int updateBlog(Blog1 blog1);
}

service

@Service
public class Blogservice {
    @Autowired
    BlogMapper blogMapper;

    @Autowired
    RestTemplate restTemplate;

    @Qualifier("com.example.openfeign.AccountOpenfeign")
    @Autowired
    AccountOpenfeign accountOpenfeign;

    @SentinelResource(value = "new-account")
    public String newAccount() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }

    public Blog1 selectBlog(int id) {
        return blogMapper.selectBlog(id);
    }

    @Transactional
    public String seata(int id) {
        Blog1 blog1 = blogMapper.selectBlog(id);
        blog1.setCoin_number(blog1.getCoin_number() + 1);
        blogMapper.updateBlog(blog1);
        accountOpenfeign.updateUser(1);
        //restTemplate.getForObject("http://account/account3/1", String.class);
        return "success";
    }
}

controller

@RestController
@RefreshScope
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    Blogservice blogservice;

    @Qualifier("com.example.openfeign.AccountOpenfeign")
    @Autowired
    AccountOpenfeign accountOpenfeign;

    @Value("${environment.name}")
    String env;

    @RequestMapping("/blog")
    @SentinelResource(value = "blog", blockHandler = "blockHandler")
    public String hello() {
        return accountOpenfeign.hello("xumeng03") + " " + env;
    }

    @RequestMapping("/blog1")
    public String hello1() {
        System.out.println("blog1");
        return accountOpenfeign.hello1("xumeng03") + " " + env;
    }

    @RequestMapping("/blog/common")
    @SentinelResource(value = "blog-common", blockHandler = "blockHandler")
    public String common() throws InterruptedException {
        Thread.sleep(5000);
        return JSON.toJSONString(new Blog("title", "content"));
    }

    public String blockHandler(BlockException blockException) {
        return "流控" + blockException.toString();
    }

    @RequestMapping("/blog/{id}")
    public String selectBlog(@PathVariable("id") int id) {
        return JSON.toJSONString(blogservice.selectBlog(id));
    }

    @RequestMapping("/blog/seata")
    public String seata() {
        return blogservice.seata(1);
    }
}

修改启动类

@SpringBootApplication
// 添加启用FeignClients
@EnableFeignClients
@MapperScan("com.example.mapper")
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

6.9、测试

测试发现正常扣减,可在Blogservice.java添加异常,此时Transactional事务将不会回滚远程服务的数据

6.10、配置分布式事务

1、account

添加依赖


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>accountartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.examplegroupId>
            <artifactId>commonartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.8version>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-seataartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

application.yaml

server:
  port: 10010
spring:
  # 应用名称
  application:
    name: account
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
        group: SEATA_GROUP
    # sentinel配置
    sentinel:
      transport:
        dashboard: localhost:8858
      web-context-unify: false
    loadbalancer:
      cache:
        enabled: false
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://150.158.24.200:3306/user?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
seata:
  enabled: true
  tx-service-group: my_test_tx_group
  service:
    # 事务群组
    vgroupMapping:
      my_test_tx_group: default  # default 的值为集群的名字,在配置 seata service 的时候指定的
  registry:
    type: nacos
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      application: seata-server
      # nacos用户名
      username: nacos
      # nacos密码
      password: nacos
      group: SEATA_GROUP
  config:
    type: nacos
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      # nacos用户名
      username: nacos
      # nacos密码
      password: nacos
      group: SEATA_GROUP
      dataId: seataServer.properties

2、blog

添加依赖


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>com.examplegroupId>
        <artifactId>springcloud-demoartifactId>
        <version>0.0.1-SNAPSHOTversion>
    parent>

    <artifactId>blogartifactId>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>com.examplegroupId>
            <artifactId>commonartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-bootstrapartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.8version>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-seataartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>${spring-boot.revision}version>
                <executions>
                    <execution>
                        <goals>
                            
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

application.yaml

server:
  port: 10020
spring:
  # 应用名称
  application:
    name: blog
  # 设置激活配置文件
  profiles:
    active: dev
  cloud:
    # nacos配置
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
        group: SEATA_GROUP
    # sentinel配置
    sentinel:
      transport:
        dashboard: localhost:8858
      web-context-unify: false
    loadbalancer:
      cache:
        enabled: false
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://150.158.24.200:3306/blog?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
logging:
  level:
    # 路径为FeignClient的路径
    com.example.openfeign.AccountOpenfeign: debug
feign:
  sentinel:
    enabled: true
seata:
  enabled: true
  enable-auto-data-source-proxy: true
  tx-service-group: my_test_tx_group
  service:
    # 事务群组
    vgroupMapping:
      my_test_tx_group: default  # default 的值为集群的名字,在配置 seata service 的时候指定的
  registry:
    type: nacos
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      application: seata-server
      # nacos用户名
      username: nacos
      # nacos密码
      password: nacos
      group: SEATA_GROUP
  config:
    type: nacos
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      # nacos用户名
      username: nacos
      # nacos密码
      password: nacos
      group: SEATA_GROUP
      dataId: seataServer.properties

service

@Service
public class Blogservice {
    @Autowired
    BlogMapper blogMapper;

    @Autowired
    RestTemplate restTemplate;

    @Qualifier("com.example.openfeign.AccountOpenfeign")
    @Autowired
    AccountOpenfeign accountOpenfeign;

    @SentinelResource(value = "new-account")
    public String newAccount() {
        return JSON.toJSONString(new Account("xumeng03", 22));
    }

    public Blog1 selectBlog(int id) {
        return blogMapper.selectBlog(id);
    }

    //@Transactional
    @GlobalTransactional
    public String seata(int id) {
        Blog1 blog1 = blogMapper.selectBlog(id);
        blog1.setCoin_number(blog1.getCoin_number() + 1);
        blogMapper.updateBlog(blog1);
        accountOpenfeign.updateUser(1);
        //restTemplate.getForObject("http://account/account3/1", String.class);
        return "success";
    }
}

6.11、测试

测试发现正常扣减,可在Blogservice.java添加异常,此时Transactional事务将回滚所有数据库操作

你可能感兴趣的:(jmeter,学习,笔记)