版本依赖关系:https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E
修改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>
子项目添加启动类和配置文件
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
<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>
子项目添加启动类和配置文件
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
<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>
这里采用docker的方式部署
如果直接在主机上部署可以在https://github.com/alibaba/nacos/releases找需要的版本
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
/*
* 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');
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
可视化界面:http://150.158.24.200:8848/nacos/
均在子项目中配置
<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>
<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>
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
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
可在面板里面打开service面板(有时候无法显示出来springboot服务面板,可以在services->±>run configuration->springboot)
服务提供者
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;
}
}
服务调用者
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);
}
}
在service面板里面选中要复制的应用,右键选择Copy Configuration
修改服务名称和端口(Environment variables如果没有的话,可以在Modify options选项里面勾选上)
<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>
<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>
// 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;
}
}
// 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");
}
}
// 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);
}
}
// 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
# 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
// 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);
}
}
# 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
配置文档:https://github.com/alibaba/spring-cloud-alibaba/wiki/Nacos-config
http://150.158.24.200:8848/nacos/#/configurationManagement
<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>
<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>
必须使用bootstrap.properties/bootstrap.yaml指定nacos server的地址
# 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
# 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
// 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;
}
}
// 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效果,结果如下小节所示
保持不变
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版本下载对应的版本: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
<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>
<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>
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
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
// 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));
}
}
// 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"));
}
}
访问几次服务接口,就可以在sentinel dashboard里面看到服务
配置服务降级
// 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 "流控";
}
}
配置服务降级
// 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();
}
}
// 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);
}
}
当接口具有资源竞争的时候,接口便有了关联,此时若重要接口访问频率变高,需要限制不重要的接口的访问
线程组配置
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
@Service
public class Blogservice {
@SentinelResource(value = "new-account")
public String newAccount() {
return JSON.toJSONString(new Account("xumeng03", 22));
}
}
@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();
}
}
@RestController
public class BlowController {
@RequestMapping("/blog/blow")
public String blow() throws InterruptedException {
Thread.sleep(2000);
return "blow";
}
}
等待一分钟,第一次访问正常,但因为超时,随后再次进入熔断
@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("自定义异常");
}
}
等待一分钟,第一次访问正常,但因为超时,随后再次进入熔断
@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 "流控";
}
}
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();
}
}
参照1.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>
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
尝试访问服务
<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>
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
尝试访问服务
待补。。。
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
<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>
可以在Api管理中设置Api分组,在流控中为Api分组设置流控
代码方式
@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': '服务繁忙'}"