SpringCloud Alibaba学习笔记

SpringCloud Alibaba学习笔记

1、项目搭建

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

在这里插入图片描述
SpringCloud Alibaba学习笔记_第1张图片

1.1、搭建父工程

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

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

修改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

创建子项目
SpringCloud Alibaba学习笔记_第4张图片

子项目添加启动类和配置文件
在这里插入图片描述

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

子项目打包方式修改
SpringCloud Alibaba学习笔记_第5张图片


<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

创建子项目
SpringCloud Alibaba学习笔记_第6张图片

子项目添加启动类和配置文件
在这里插入图片描述

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

子项目打包方式修改
SpringCloud Alibaba学习笔记_第7张图片


<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
SpringCloud Alibaba学习笔记_第8张图片
SpringCloud Alibaba学习笔记_第9张图片

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)
SpringCloud Alibaba学习笔记_第10张图片

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);
    }
}

SpringCloud Alibaba学习笔记_第11张图片

2.8、应用启动多实例

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

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、添加配置

SpringCloud Alibaba学习笔记_第13张图片

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;
    }
}

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

SpringCloud Alibaba学习笔记_第15张图片

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

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

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里面看到服务
SpringCloud Alibaba学习笔记_第17张图片

SpringCloud Alibaba学习笔记_第18张图片

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 "流控";
    }
}

添加流控
SpringCloud Alibaba学习笔记_第19张图片

SpringCloud Alibaba学习笔记_第20张图片

多刷新几次
SpringCloud Alibaba学习笔记_第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();
    }
}

添加流控
SpringCloud Alibaba学习笔记_第22张图片

SpringCloud Alibaba学习笔记_第23张图片

多刷新几次
SpringCloud Alibaba学习笔记_第24张图片

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、设置流控

SpringCloud Alibaba学习笔记_第25张图片

3、测试

在这里插入图片描述

5.9、限流(关联)

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

1、添加流控

SpringCloud Alibaba学习笔记_第26张图片

SpringCloud Alibaba学习笔记_第27张图片

2、Jmeter访问

线程组配置
在这里插入图片描述

取样器配置
SpringCloud Alibaba学习笔记_第28张图片

3、测试

SpringCloud Alibaba学习笔记_第29张图片

SpringCloud Alibaba学习笔记_第30张图片

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、修改流控

SpringCloud Alibaba学习笔记_第31张图片

SpringCloud Alibaba学习笔记_第32张图片

5、测试

SpringCloud Alibaba学习笔记_第33张图片

5.11、熔断(慢调用)

1、controller

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

2、修改熔断

SpringCloud Alibaba学习笔记_第34张图片

SpringCloud Alibaba学习笔记_第35张图片

3、测试

SpringCloud Alibaba学习笔记_第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、修改熔断

SpringCloud Alibaba学习笔记_第37张图片
SpringCloud Alibaba学习笔记_第38张图片

3、测试

SpringCloud Alibaba学习笔记_第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、测试

SpringCloud Alibaba学习笔记_第40张图片

6、Gateway

6.1、新建模块

参照1.2

6.2、添加依赖


<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>gatewayartifactId>

    <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-gatewayartifactId>
        dependency>
    dependencies>

project>

6.3、修改配置

server:
  port: 10030
spring:
  # 应用名称
  application:
    name: gateway
  # 需要排除spring-boot-starter-web
  main:
    web-application-type: reactive
  cloud:
    gateway:
      routes:
        - id: account-router
          uri: http://localhost:10010
          predicates:
            - Path=/account-api/**
          filters:
            - StripPrefix=1
        - id: blog-router
          uri: http://localhost:10020
          predicates:
            - Path=/blog-api/**
          filters:
            - StripPrefix=1

6.4、测试

尝试访问服务

6.5、整合nacos

1、添加依赖


<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>gatewayartifactId>

    <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-gatewayartifactId>
        dependency>
        <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>

project>

2、修改配置

server:
  port: 10030
spring:
  # 应用名称
  application:
    name: gateway
  # 需要排除spring-boot-starter-web
  main:
    web-application-type: reactive
  cloud:
    gateway:
      routes:
        - id: account-router
          uri: lb://account
          predicates:
            - Path=/account-api/**
          filters:
            - StripPrefix=1
        - id: blog-router
          uri: lb://blog
          predicates:
            - Path=/blog-api/**
          filters:
            - StripPrefix=1
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public

3、测试

尝试访问服务

6.6、内置断言工厂

1、DateTime

2、IP

3、Cookie

4、Header

5、Host

6、Method

7、Path

8、Parameter

9、路由权重

6.7、过滤器

待补。。。

6.9、跨域配置

server:
  port: 10030
spring:
  # 应用名称
  application:
    name: gateway
  # 需要排除spring-boot-starter-web
  main:
    web-application-type: reactive
  cloud:
    gateway:
      routes:
        - id: account-router
          uri: lb://account
          predicates:
            - Path=/account-api/**
          filters:
            - StripPrefix=1
        - id: blog-router
          uri: lb://blog
          predicates:
            - Path=/blog-api/**
          filters:
            - StripPrefix=1
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
              - GET
              - HEAD
              - POST
              - PUT
              - DELETE
              - TRACE
              - OPTIONS
              - PATCH
            allowedHeaders: "*"
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public

6.10、整合sentinel

1、添加依赖


<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>gatewayartifactId>

    <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-gatewayartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-loadbalancerartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-sentinel-gatewayartifactId>
        dependency>
    dependencies>

project>

2、sentinel控制台

SpringCloud Alibaba学习笔记_第41张图片

3、添加流控

SpringCloud Alibaba学习笔记_第42张图片

4、测试

SpringCloud Alibaba学习笔记_第43张图片

5、API分组

可以在Api管理中设置Api分组,在流控中为Api分组设置流控
SpringCloud Alibaba学习笔记_第44张图片

SpringCloud Alibaba学习笔记_第45张图片

6、自定义异常

代码方式

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomSentinelResult {
    private int code;
    private String message;
    private Date date;
}
@Configuration
public class SentinelException {
    @PostConstruct
    public void init() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                CustomSentinelResult sentinelResult = new CustomSentinelResult(HttpStatus.SC_TOO_MANY_REQUESTS, "服务繁忙", new Date());
                return ServerResponse.status(HttpStatus.SC_TOO_MANY_REQUESTS)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(sentinelResult));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}

配置文件方式

server:
  port: 10030
spring:
  # 应用名称
  application:
    name: gateway
  # 需要排除spring-boot-starter-web
  main:
    web-application-type: reactive
  cloud:
    gateway:
      routes:
        - id: account-router
          uri: lb://account
          predicates:
            - Path=/account-api/**
          filters:
            - StripPrefix=1
        - id: blog-router
          uri: lb://blog
          predicates:
            - Path=/blog-api/**
          filters:
            - StripPrefix=1
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
              - GET
              - HEAD
              - POST
              - PUT
              - DELETE
              - TRACE
              - OPTIONS
              - PATCH
            allowedHeaders: "*"
    nacos:
      # nacos地址
      server-addr: 150.158.24.200:8848
      discovery:
        # nacos用户名
        username: nacos
        # nacos密码
        password: nacos
        # nacos命名空间
        namespace: public
    sentinel:
      transport:
        dashboard: localhost:8858
      scg:
        fallback:
          mode: response
          response-body: "{'code': 429, 'message': '服务繁忙'}"

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