

|
第一代
Spring Cloud
(
Netflix
,
SCN
)
|
第二代
Spring Cloud
(主要就是
Spring
Cloud Alibaba
,
SCA
)
| |
|
注册中心
|
Netflix Eureka
|
阿里巴巴
Nacos
|
|
客户端负
载均衡
|
Netflix Ribbon
|
阿里巴巴
Dubbo LB
、
Spring Cloud
Loadbalancer
|
|
熔断器
|
Netflix Hystrix
| 阿里巴巴 Sentinel |
|
网关
|
Netflix Zuul
:性能一般,未来将退出
Spring Cloud
生态圈
|
官方
Spring Cloud Gateway
|
|
配置中心
|
官方
Spring Cloud Config
|
阿里巴巴
Nacos
、携程
Apollo
|
|
服务调用
|
Netflix Feign
|
阿里巴巴
Dubbo RPC
|
|
消息驱动
|
官方
Spring Cloud Stream
| |
|
链路追踪
|
官方
Spring Cloud Sleuth/Zipkin
| |
|
阿里巴巴
seata
分布式事务方案
|
完整业务流程图:

- CREATE TABLE products(
- id INT PRIMARY KEY AUTO_INCREMENT,
- NAME VARCHAR(50), #商品名称
- price DOUBLE,
- flag VARCHAR(2), #上架状态
- goods_desc VARCHAR(100), #商品描述
- images VARCHAR(400), #商品图片
- goods_stock INT, #商品库存
- goods_type VARCHAR(20) #商品类型
- );
- <packaging>pompackaging>
- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-parentartifactId>
- <version>2.1.6.RELEASEversion>
- parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-loggingartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>1.18.4version>
- <scope>providedscope>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-devtoolsartifactId>
- <optional>trueoptional>
- dependency>
- dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-compiler-pluginartifactId>
- <configuration>
- <source>11source>
- <target>11target>
- <encoding>utf-8encoding>
- configuration>
- plugin>
- <plugin>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-maven-pluginartifactId>
- <executions>
- <execution>
- <goals>
- <goal>repackagegoal>
- goals>
- execution>
- executions>
- plugin>
- plugins>
- build>
- "1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
- http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>lagou-parentartifactId>
- <groupId>com.lagougroupId>
- <version>1.0-SNAPSHOTversion>
- parent>
- <modelVersion>4.0.0modelVersion>
- <artifactId>lagou-service-commonartifactId>
- <dependencies>
- <dependency>
- <groupId>com.baomidougroupId>
- <artifactId>mybatis-plus-boot-starterartifactId>
- <version>3.3.2version>
- dependency>
- <dependency>
- <groupId>javax.persistencegroupId>
- <artifactId>javax.persistence-apiartifactId>
- <version>2.2version>
- dependency>
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <scope>runtimescope>
- dependency>
- dependencies>
- project>
- package com.lagou.common.pojo;
- import lombok.Data;
- import javax.persistence.Id;
- import javax.persistence.Table;
- @Data
- @Table(name = "products")
- public class Products {
- @Id
- private Integer id;
- private String name;
- private double price;
- private String flag;
- private String goodsDesc;
- private String images;
- private long goodsStock;
- private String goodsType;
- }
- <dependencies>
- <dependency>
- <groupId>com.lagougroupId>
- <artifactId>lagou-service-commonartifactId>
- <version>1.0-SNAPSHOTversion>
- dependency>
- dependencies>
- server:
- port: 9000 # 后期该微服务多实例,9000(10个以内)
- Spring:
- application:
- name: lagou-service-product
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/lagou?
- useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
- username: root
- password: wu7787879
- package com.lagou.product.mapper;
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.baomidou.mybatisplus.core.mapper.Mapper;
- import com.lagou.common.pojo.Products;
- /**
- * 现在使用的Mybatis-plus组件,该组件是Mybatis的加强版
- * 能够与SpringBoot进行非常友好的整合,对比Mybatis框架只有使用便捷的改变
- * 没有具体功能的改变
- * 具体使用:让具体的Mapper接口继承BaseMapper即可
- */
- public interface ProductMapper extends BaseMapper
{ - }
- package com.lagou.product.service.impl;
- import com.lagou.common.pojo.Products;
- import com.lagou.product.mapper.ProductMapper;
- import com.lagou.product.service.ProductService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- @Service
- public class ProductServiceImpl implements ProductService {
- @Autowired
- private ProductMapper productMapper;
- /**
- * 根据商品ID查询商品对象
- */
- @Override
- public Products findById(Integer productId) {
- return productMapper.selectById(productId);
- }
- }
- package com.lagou.product.controller;
- import com.lagou.common.pojo.Products;
- import com.lagou.product.service.ProductService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @RequestMapping("/product")
- public class ProductController {
- @Autowired
- private ProductService productService;
- @RequestMapping("/query/{id}")
- public Products query(@PathVariable Integer id){
- return productService.findById(id);
- }
- }
- package com.lagou.product;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- @MapperScan("com.lagou.product.mapper")
- public class ProductApplication {
- public static void main(String[] args) {
- SpringApplication.run(ProductApplication.class,args);
- }
- }
- "1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
- http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>lagou-parentartifactId>
- <groupId>com.lagougroupId>
- <version>1.0-SNAPSHOTversion>
- parent>
- <modelVersion>4.0.0modelVersion>
- <artifactId>lagou-service-pageartifactId>
- <dependencies>
- <dependency>
- <groupId>com.lagougroupId>
- <artifactId>lagou-service-commonartifactId>
- <version>1.0-SNAPSHOTversion>
- dependency>
- dependencies>
- project>
- server:
- port: 9100 # 后期该微服务多实例,端口从9100递增(10个以内)
- Spring:
- application:
- name: lagou-service-page
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/lagou?
- useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
- username: root
- password: wu7787879
- package com.lagou.page.controller;
- import com.lagou.common.pojo.Products;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.client.RestTemplate;
- @RestController
- @RequestMapping("/page")
- public class PageController {
- @Autowired
- private RestTemplate restTemplate;
- @GetMapping("/getData/{id}")
- public Products findDataById(@PathVariable Integer id){
- Products products =
- restTemplate.getForObject("http://localhost:9000/product/query/"+id,
- Products.class);
- System.out.println("从lagou-service-product获得product对象:"+products);
- return products;
- }
- }
- package com.lagou.page;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.context.annotation.Bean;
- import org.springframework.web.client.RestTemplate;
- import java.awt.print.Pageable;
- @SpringBootApplication
- public class PageApplication {
- public static void main(String[] args) {
- SpringApplication.run(PageApplication.class,args);
- }
- @Bean
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }
- }
|
组件名
|
语言
|
CAP
|
对外暴露接口
|
|
Eureka
|
Java
|
AP
(自我保护机制,保证可用)
|
HTTP
|
|
Consul
|
Go
|
CP
|
HTTP/DNS
|
|
Zookeeper
|
Java
|
CP
|
客户端
|
|
Nacos
|
Java
|
支持
AP/CP
切换
|
HTTP
|
Eureka 交互流程及原理

Spring Cloud 是一个综合的项目,下面有很多子项目,比如eureka子项目
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-dependenciesartifactId>
- <version>Greenwich.RELEASEversion>
- <type>pomtype>
- <scope>importscope>
- dependency>
- dependencies>
- dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
- dependency>
- dependencies>
- <dependency>
- <groupId>com.sun.xml.bindgroupId>
- <artifactId>jaxb-coreartifactId>
- <version>2.2.11version>
- dependency>
- <dependency>
- <groupId>javax.xml.bindgroupId>
- <artifactId>jaxb-apiartifactId>
- dependency>
- <dependency>
- <groupId>com.sun.xml.bindgroupId>
- <artifactId>jaxb-implartifactId>
- <version>2.2.11version>
- dependency>
- <dependency>
- <groupId>org.glassfish.jaxbgroupId>
- <artifactId>jaxb-runtimeartifactId>
- <version>2.2.10-b140310.1920version>
- dependency>
- <dependency>
- <groupId>javax.activationgroupId>
- <artifactId>activationartifactId>
- <version>1.1.1version>
- dependency>
- #Eureka server服务端口
- server:
- port: 9200
- spring:
- application:
- name: lagou-cloud-eureka-server # 应用名称,会在Eureka中作为服务的id标识
- (serviceId)
- eureka:
- instance:
- hostname: localhost
- client:
- service-url: # 客户端与EurekaServer交互的地址,如果是集群,也需要写其它Server的地址
- defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- register-with-eureka: false # 自己就是服务不需要注册自己
- fetch-registry: false #自己就是服务不需要从Eureka Server获取服务信息,默认为true,置
- 为false
- package com.lagou.eureka;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
- @SpringBootApplication
- 声明本项目是一个Eureka服务
- @EnableEurekaServer
- public class EurekaApplication {
- public static void main(String[] args) {
- SpringApplication.run(EurekaApplication.class,args);
- }
- }


6、商品微服务和页面静态化微服务注册到Eureka
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
- dependency>
- eureka:
- client:
- serviceUrl: # eureka server的路径
- defaultZone: http://localhost:9200/eureka/
- instance:
- #使用ip注册,否则会使用主机名注册了(此处考虑到对老版本的兼容,新版本经过实验都是ip)
- prefer-ip-address: true
- #自定义实例显示格式,加上版本号,便于多版本管理,注意是ip-address,早期版本是ipAddress
- instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
- @SpringBootApplication
- @EnableDiscoveryClient //@EnableEurekaClient
- public class PageApplication {
- public static void main(String[] args) {
- SpringApplication.run(PageApplication.class,args);
- }
- @Bean
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }
- }
- 127.0.0.1 LagouCloudEurekaServerA
- 127.0.0.1 LagouCloudEurekaServerB
- #Eureka server服务端口
- server:
- port: 9200
- spring:
- application:
- name: lagou-cloud-eureka-server # 应用名称,会在Eureka中作为服务的id标识
- (serviceId)
- eureka:
- instance:
- hostname: LagouCloudEurekaServerA
- client:
- register-with-eureka: true
- fetch-registry: true
- serviceUrl:
- defaultZone: http://LagouCloudEurekaServerB:9201/eureka
- #Eureka server服务端口
- server:
- port: 9201
- spring:
- application:
- name: lagou-cloud-eureka-server # 应用名称,会在Eureka中作为服务的id标识
- (serviceId)
- eureka:
- instance:
- hostname: LagouCloudEurekaServerB
- client:
- register-with-eureka: true
- fetch-registry: true
- serviceUrl:
- defaultZone: http://LagouCloudEurekaServerA:9200/eureka
- server:
- port: 9000 # 后期该微服务多实例,9000(10个以内)
- Spring:
- application:
- name: lagou-service-product
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/lagou?
- useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
- username: root
- password: wu7787879
- eureka:
- client:
- serviceUrl: # eureka server的路径
- defaultZone:
- http://lagoucloudeurekaservera:9200/eureka/,http://lagoucloudeurekaserverb:9201/
- eureka/ #把 eureka 集群中的所有 url 都填写了进来,也可以只写一台,因为各个 eureka server
- 可以同步注册表
- instance:
- #使用ip注册,否则会使用主机名注册了(此处考虑到对老版本的兼容,新版本经过实验都是ip)
- prefer-ip-address: true
- #自定义实例显示格式,加上版本号,便于多版本管理,注意是ip-address,早期版本是ipAddress
- instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
- server:
- port: 9100 # 后期该微服务多实例,端口从9100递增(10个以内)
- Spring:
- application:
- name: lagou-service-page
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/lagou?
- useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
- username: root
- password: wu7787879
- eureka:
- client:
- serviceUrl: # eureka server的路径
- defaultZone:
- http://lagoucloudeurekaservera:9200/eureka/,http://lagoucloudeurekaserverb:9201/
- eureka/ #把 eureka 集群中的所有 url 都填写了进来,也可以只写一台,因为各个 eureka server
- 可以同步注册表
- instance:
- #使用ip注册,否则会使用主机名注册了(此处考虑到对老版本的兼容,新版本经过实验都是ip)
- prefer-ip-address: true
- #自定义实例显示格式,加上版本号,便于多版本管理,注意是ip-address,早期版本是ipAddress
- instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
- @RestController
- @RequestMapping("/page")
- public class PageController {
- @Autowired
- private RestTemplate restTemplate;
- @Autowired
- private DiscoveryClient discoveryClient;
- @RequestMapping("/getData/{id}")
- public Products findDataById(@PathVariable Integer id){
- //1.获得Eureka中注册的lagou-service-product实例集合
- List
instances = discoveryClient.getInstances("lagouservice-product"); - //2.获得实例集合中的第一个
- ServiceInstance instance = instances.get(0);
- //3.根据实例信息拼接IP地址
- String host = instance.getHost();
- int port = instance.getPort();
- String url = "http://"+host+":"+port+"/product/query/"+id;
- //4.调用
- Products products = restTemplate.getForObject(url, Products.class);
- System.out.println("从lagou-service-product获得product对象:"+products);
- return products;
- }
- }
- instance:
- #使用ip注册,否则会使用主机名注册了(此处考虑到对老版本的兼容,新版本经过实验都是ip)
- prefer-ip-address: true
- #自定义实例显示格式,加上版本号,便于多版本管理,注意是ip-address,早期版本是ipAddress
- instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
- metadata-map:
- ip: 192.168.200.128
- port: 10000
- user: YuanJing
- pwd: 123456
- package com.lagou.page.controller;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.cloud.client.ServiceInstance;
- import org.springframework.cloud.client.discovery.DiscoveryClient;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- @RestController
- @RequestMapping("/metadata")
- public class MetadataController {
- @Autowired
- private DiscoveryClient discoveryClient;
- @RequestMapping("show")
- public String showMetadata(){
- String result = "";
- List
instances = discoveryClient.getInstances("lagouservice-page"); - for (ServiceInstance instance:instances) {
- //获取服务元数据
- Map
metadata = instance.getMetadata(); - Set
> entries = metadata.entrySet(); - for (Map.Entry
entry : entries){ - String key = entry.getKey();
- String value = entry.getValue();
- result+="key:"+key+",value:"+value;
- }
- }
- return result;
- }
- }

- #向Eureka服务中心集群注册服务
- eureka:
- instance:
- # 租约续约间隔时间,默认30秒
- lease-renewal-interval-in-seconds: 30
- # 租约到期,服务时效时间,默认值90秒,服务超过90秒没有发生心跳,EurekaServer会将服务从列
- 表移除
- lease-expiration-duration-in-seconds: 90
- #向Eureka服务中心集群注册服务
- eureka:
- client:
- # 每隔多久拉取一次服务列表
- registry-fetch-interval-seconds: 30
- eureka:
- server:
- enable-self-preservation: false # 关闭自我保护模式(缺省为打开)
- @SpringBootApplication
- @EnableDiscoveryClient //@EnableEurekaClient
- public class PageApplication {
- public static void main(String[] args) {
- SpringApplication.run(PageApplication.class,args);
- }
- @Bean
- //Ribbon负载均衡
- @LoadBalanced
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }
- }
- @RestController
- @RequestMapping("/server")
- public class ServerConfigController {
- @Value("${server.port}")
- private String serverPort;
- @requestMapping("query")
- public String findServerPort(){
- return serverPort;
- }
- }
- @RequestMapping("/getPort")
- public String getProductServerPort(){
- String url = "http://lagou-service-product/server/query";
- return restTemplate.getForObject(url,String.class);
- }
- package com.netflix.loadbalancer;
- /**
- * Interface that defines a "Rule" for a LoadBalancer. A Rule can be thought of
- * as a Strategy for loadbalacing. Well known loadbalancing strategies include
- * Round Robin, Response Time based etc.
- *
- * @author stonse
- *
- */
- public interface IRule{
- /*
- * choose one alive server from lb.allServers or
- * lb.upServers according to key
- *
- * @return choosen Server object. NULL is returned if none
- * server is available
- */
- public Server choose(Object key);
- public void setLoadBalancer(ILoadBalancer lb);
- public ILoadBalancer getLoadBalancer();
- }

|
负载均衡策略
|
描述
|
|
RoundRobinRule
:轮询策
略
|
默认超过
10
次获取到的
server
都不可用,会返回一个空的
server
|
|
RandomRule
:随机策略
|
如果随机到的
server
为
null
或者不可用的话,会
while
不停的循环选
取
|
|
RetryRule
:重试策略
|
一定时限内循环重试。默认继承
RoundRobinRule
,也支持自定义
注入,
RetryRule
会在每次选取之后,对选举的
server
进行判断,是
否为
null
,是否
alive
,并且在
500ms
内会不停的选取判断。而
RoundRobinRule
失效的策略是超过
10
次,
RandomRule
是没有失
效时间的概念,只要
serverList
没都挂。
|
|
BestAvailableRule
:最小
连接数策略
|
遍历
serverList
,选取出可用的且连接数最小的一个
server
。该算法
里面有一个
LoadBalancerStats
的成员变量,会存储所有
server
的
运行状况和连接数。如果选取到的
server
为
null
,那么会调用
RoundRobinRule
重新选取。
|
|
AvailabilityFilteringRule
:
可用过滤策略
|
扩展了轮询策略,会先通过默认的轮询选取一个
server
,再去判断
该
server
是否超时可用,当前连接数是否超限,都成功再返回。
|
|
ZoneAvoidanceRule
:区
域权衡策略
(默认策略)
|
扩展了轮询策略,继承了
2
个过滤器:
ZoneAvoidancePredicate
和
AvailabilityPredicate
,除了过滤超时和链接数过多的
server
,还会
过滤掉不符合要求的
zone
区域里面的所有节点, 在一个区域
/
机房
内的服务实例中轮询。
先过滤再轮询
|
- #针对的被调用方微服务名称,不加就是全局生效
- lagou-service-product:
- ribbon:
- NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机策略
- lagou-service-product:
- ribbon:
- NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #轮询策略
老规矩:SpringCloud充分利用了SpringBoot的自动装配特点,找spring.factories配置文件
- org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
- org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration

自动注入:



- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
- dependency>
- /**
- * 注解简化写法
- * @SpringCloudApplication =
- @SpringBootApplication+@EnableDiscoveryClient+@EnableCircuitBreaker
- */
- @SpringBootApplication
- @EnableDiscoveryClient //@EnableEurekaClient
- @EnableCircuitBreaker // 开启熔断
- public class PageApplication {
- public static void main(String[] args) {
- SpringApplication.run(PageApplication.class,args);
- }
- @Bean
- @LoadBalanced//Ribbon负载均衡
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }
- }
- /**
- * 提供者模拟处理超时,调用方法添加Hystrix控制
- */
- // 使用@HystrixCommand注解进行熔断控制
- @HystrixCommand(
- // 线程池标识,要保持唯一,不唯一的话就共用了
- threadPoolKey = "getProductServerPort2",
- // 线程池细节属性配置
- threadPoolProperties = {
- @HystrixProperty(name="coreSize",value = "1"), // 线程数
- @HystrixProperty(name="maxQueueSize",value="20") // 等待队列长
- 度
- },
- // commandProperties熔断的一些细节属性配置
- commandProperties = {
- // 每一个属性都是一个HystrixProperty
- @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value=
- "2000")
- }
- )
- @RequestMapping("/getPort2")
- public String getProductServerPort2(){
- String url = "http://lagou-service-product/server/query";
- return restTemplate.getForObject(url,String.class);
- }
- @RestController
- @RequestMapping("/server")
- public class ServerConfigController {
- @Value("${server.port}")
- private String serverPort;
- @RequestMapping("/query")
- public String findServerPort(){
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return serverPort;
- }
- }
- @HystrixCommand(
- // 线程池标识,要保持唯一,不唯一的话就共用了
- threadPoolKey = "getProductServerPort3TimeoutFallback",
- // 线程池细节属性配置
- threadPoolProperties = {
- @HystrixProperty(name = "coreSize", value = "2"), // 线程数
- @HystrixProperty(name = "maxQueueSize", value = "20") // 等待
- 队列长度
- },
- // commandProperties熔断的一些细节属性配置
- commandProperties = {
- // 每一个属性都是一个HystrixProperty
- @HystrixProperty(name =
- "execution.isolation.thread.timeoutInMilliseconds", value = "2000"),
- // hystrix高级配置,定制工作过程细节
- // 统计时间窗口定义
- @HystrixProperty(name =
- "metrics.rollingStats.timeInMilliseconds", value = "8000"),
- // 统计时间窗口内的最小请求数
- @HystrixProperty(name =
- "circuitBreaker.requestVolumeThreshold", value = "2"),
- // 统计时间窗口内的错误数量百分比阈值
- @HystrixProperty(name =
- "circuitBreaker.errorThresholdPercentage", value = "50"),
- // 自我修复时的活动窗口长度
- @HystrixProperty(name =
- "circuitBreaker.sleepWindowInMilliseconds", value = "3000")
- },
- fallbackMethod = "myFallBack" // 回退方法
- )
- @RequestMapping("/getPort3")
- public String getProductServerPort3() {
- String url = "http://lagou-service-product/server/query";
- return restTemplate.getForObject(url, String.class);
- }
- /**
- * 定义回退方法,返回预设默认值
- * 注意:该方法形参和返回值与原始方法保持一致
- */
- public String myFallBack() {
- return "-1"; // 兜底数据
- }
- /**
- * 8秒钟内,请求次数达到2个,并且失败率在50%以上,就跳闸
- * 跳闸后活动窗口设置为3s
- */
- @HystrixCommand(
- commandProperties = {
- //统计窗口时间的设置
- @HystrixProperty(name =
- "metrics.rollingStats.timeInMilliseconds",value = "8000"),
- //统计窗口内的最小请求数
- @HystrixProperty(name =
- "circuitBreaker.requestVolumeThreshold",value = "2"),
- //统计窗口内错误请求阈值的设置 50%
- @HystrixProperty(name =
- "circuitBreaker.errorThresholdPercentage",value = "50"),
- //自我修复的活动窗口时间
- @HystrixProperty(name =
- "circuitBreaker.sleepWindowInMilliseconds",value = "3000")
- }
- )
- # 配置熔断策略:
- hystrix:
- command:
- default:
- circuitBreaker:
- # 强制打开熔断器,如果该属性设置为true,强制断路器进入打开状态,将会拒绝所有的请求。
- 默认false关闭的
- forceOpen: false
- # 触发熔断错误比例阈值,默认值50%
- errorThresholdPercentage: 50
- # 熔断后休眠时长,默认值5秒
- sleepWindowInMilliseconds: 3000
- # 熔断触发最小请求次数,默认值是20
- requestVolumeThreshold: 2
- execution:
- isolation:
- thread:
- # 熔断超时设置,默认为1秒
- timeoutInMilliseconds: 2000
- # springboot中暴露健康检查等断点接口
- management:
- endpoints:
- web:
- exposure:
- include: "*"
- # 暴露健康接口的细节
- endpoint:
- health:
- show-details: always
- hystrix:
- threadpool:
- default:
- coreSize: 10 #并发执行的最大线程数,默认10
- maxQueueSize: 1000 #BlockingQueue的最大队列数,默认值-1
- queueSizeRejectionThreshold: 800 #即使maxQueueSize没有达到,达到
- queueSizeRejectionThreshold该值后,请求也会被拒绝,默认值5
- hystrix:
- threadpool:
- default:
- coreSize: 10
- maxQueueSize: 1500
- queueSizeRejectionThreshold: 1000
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
- @SpringBootApplication
- @EnableDiscoveryClient // 开启服务发现
- @EnableFeignClients // 开启Feign
- public class PageApplication {
- public static void main(String[] args) {
- SpringApplication.run(PageApplication.class,args);
- }
- }
- @FeignClient(name = "lagou-service-product")
- public interface ProductFeign {
- /**
- * 通过id获取商品信息
- * @param id
- * @return
- */
- @RequestMapping("/product/query/{id}")
- public Products query(@PathVariable Integer id);
- /**
- * 获得端口号
- * @return
- */
- @RequestMapping("/server/query")
- public String findServerPort();
- }
- @RestController
- @RequestMapping("/page")
- public class PageController {
- @Autowired
- private ProductFeign productFeign;
- @RequestMapping("/getData/{id}")
- public Products findDataById(@PathVariable Integer id) {
- return productFeign.query(id);
- }
- @RequestMapping("/getPort")
- public String getProductServerPort() {
- return productFeign.findServerPort();
- }
- }
- #针对的被调用方微服务名称,不加就是全局生效
- lagou-service-product:
- ribbon:
- #请求连接超时时间
- #ConnectTimeout: 2000
- #请求处理超时时间
- #ReadTimeout: 5000
- #对所有操作都进行重试
- OkToRetryOnAllOperations: true
- ####根据如上配置,当访问到故障请求的时候,它会再尝试访问一次当前实例(次数由
- MaxAutoRetries配置),
- ####如果不行,就换一个实例进行访问,如果还不行,再换一次实例访问(更换次数由
- MaxAutoRetriesNextServer配置),
- ####如果依然不行,返回失败信息。
- MaxAutoRetries: 0 #对当前选中实例重试次数,不包括第一次调用
- MaxAutoRetriesNextServer: 0 #切换实例的重试次数
- NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #负载策略
- 调整
- # 开启Feign的熔断功能
- feign:
- hystrix:
- enabled: true
- hystrix:
- command:
- default:
- circuitBreaker:
- # 强制打开熔断器,如果该属性设置为true,强制断路器进入打开状态,将会拒绝所有的请求。
- 默认false关闭的
- forceOpen: false
- # 触发熔断错误比例阈值,默认值50%
- errorThresholdPercentage: 50
- # 熔断后休眠时长,默认值5秒
- sleepWindowInMilliseconds: 3000
- # 熔断触发最小请求次数,默认值是20
- requestVolumeThreshold: 2
- execution:
- isolation:
- thread:
- # 熔断超时设置,默认为1秒
- timeoutInMilliseconds: 5000
- package com.lagou.page.feign.fallback;
- import com.lagou.common.pojo.Products;
- import com.lagou.page.feign.ProductFeign;
- import org.springframework.stereotype.Component;
- @Component
- public class ProductFeignFallBack implements ProductFeign {
- @Override
- public Products query(Integer id) {
- return null;
- }
- @Override
- public String findServerPort() {
- return "-1";
- }
- }
- @FeignClient(name = "lagou-service-product",fallback =
- ProductFeignFallBack.class)
- public interface ProductFeign {
- /**
- * 通过商品id查询商品对象
- * @param id
- * @return
- */
- @GetMapping("/product/query/{id}")
- public Products queryById(@PathVariable Integer id);
- @GetMapping("/service/port")
- public String getPort();
- }
- feign:
- hystrix:
- enabled: true
- #开启请求和响应压缩
- compression:
- request:
- enabled: true #默认不开启
- mime-types: text/html,application/xml,application/json # 设置压缩的数据类型,
- 此处也是默认值
- min-request-size: 2048 # 设置触发压缩的大小下限,此处也是默认值
- response:
- enabled: true #默认不开启
- "1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
- http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0modelVersion>
- <groupId>com.lagougroupId>
- <artifactId>lagou-cloud-gatewayartifactId>
- <version>1.0-SNAPSHOTversion>
- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-parentartifactId>
- <version>2.1.6.RELEASEversion>
- parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-commonsartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-gatewayartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webfluxartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-loggingartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>1.18.4version>
- <scope>providedscope>
- dependency>
- <dependency>
- <groupId>com.sun.xml.bindgroupId>
- <artifactId>jaxb-coreartifactId>
- <version>2.2.11version>
- dependency>
- <dependency>
- <groupId>javax.xml.bindgroupId>
- <artifactId>jaxb-apiartifactId>
- dependency>
- <dependency>
- <groupId>com.sun.xml.bindgroupId>
- <artifactId>jaxb-implartifactId>
- <version>2.2.11version>
- dependency>
- <dependency>
- <groupId>org.glassfish.jaxbgroupId>
- <artifactId>jaxb-runtimeartifactId>
- <version>2.2.10-b140310.1920version>
- dependency>
- <dependency>
- <groupId>javax.activationgroupId>
- <artifactId>activationartifactId>
- <version>1.1.1version>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-devtoolsartifactId>
- <optional>trueoptional>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-sleuthartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-zipkinartifactId>
- dependency>
- dependencies>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-dependenciesartifactId>
- <version>Greenwich.RELEASEversion>
- <type>pomtype>
- <scope>importscope>
- dependency>
- dependencies>
- dependencyManagement>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-compiler-pluginartifactId>
- <configuration>
- <source>11source>
- <target>11target>
- <encoding>utf-8encoding>
- configuration>
- plugin>
- <plugin>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-maven-pluginartifactId>
- plugin>
- plugins>
- build>
- project>
- server:
- port: 9300
- eureka:
- client:
- serviceUrl: # eureka server的路径
- defaultZone:
- http://LagouCloudEurekaServerA:9200/eureka,http://LagouCloudEurekaServerB:9201/e
- ureka
- instance:
- prefer-ip-address: true
- instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
- spring:
- application:
- name: lagou-cloud-gateway
- #网关的配置
- cloud:
- gateway:
- routes: #配置路由
- - id: service-page-router
- uri: http://127.0.0.1:9100
- predicates: #当断言成功后,交给某一个微服务处理时使用的是转发
- - Path=/page/**
- - id: service-product-router
- uri: http://127.0.0.1:9000
- predicates:
- - Path=/product/**
- filters:
- # http://127.0.0.1:9300/product/service/port --> /service/port -->
- 商品微服务
- - StripPrefix=1 #去掉uri中的第一部分,所以就要求我们通过网关访问的时候,把uri
- 的第一部分设置为product,从uri的第二部分开始才是真正的uri



启动类
- package com.lagou.gateway;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- @SpringBootApplication
- @EnableDiscoveryClient
- public class GatewayApplication {
- public static void main(String[] args) {
- SpringApplication.run(GatewayApplication.class,args);
- }
- }
时间点后匹配
- spring:
- cloud:
- gateway:
- routes:
- - id: after_route
- uri: https://example.org
- predicates:
- - After=2017-01-20T17:42:47.789-07:00[America/Denver]
- spring:
- cloud:
- gateway:
- routes:
- - id: before_route
- uri: https://example.org
- predicates:
- - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
- spring:
- cloud:
- gateway:
- routes:
- - id: between_route
- uri: https://example.org
- predicates:
- - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-
- 21T17:42:47.789-07:00[America/Denver]
- spring:
- cloud:
- gateway:
- routes:
- - id: cookie_route
- uri: https://example.org
- predicates:
- - Cookie=chocolate, ch.p
- spring:
- cloud:
- gateway:
- routes:
- - id: header_route
- uri: https://example.org
- predicates:
- - Header=X-Request-Id, \d+
- spring:
- cloud:
- gateway:
- routes:
- - id: host_route
- uri: https://example.org
- predicates:
- - Host=**.somehost.org,**.anotherhost.org
- spring:
- cloud:
- gateway:
- routes:
- - id: method_route
- uri: https://example.org
- predicates:
- - Method=GET,POST
- spring:
- cloud:
- gateway:
- routes:
- - id: path_route
- uri: https://example.org
- predicates:
- - Path=/red/{segment},/blue/{segment}
- spring:
- cloud:
- gateway:
- routes:
- - id: query_route
- uri: https://example.org
- predicates:
- - Query=green
- spring:
- cloud:
- gateway:
- routes:
- - id: query_route
- uri: https://example.org
- predicates:
- - Query=red, gree.
- spring:
- cloud:
- gateway:
- routes:
- - id: remoteaddr_route
- uri: https://example.org
- predicates:
- - RemoteAddr=192.168.1.1/24
|
生命周
期时机
点
|
作用
|
|
pre
|
这种过滤器在请求被路由之前调用。我们可利用这种过滤器实现身份验证、在集群中选 择请求的微服务、记录调试信息等。
|
|
post
|
这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的
HTTP
Header
、收集统计信息和指标、将响应从微服务发送给客户端等。
|
|
过滤器类型
|
影响范围
|
|
GateWayFilter
|
应用到单个路由路由上
|
|
GlobalFilter
|
应用到所有的路由上
|
- predicates:
- - Path=/product/**
- filters:
- - StripPrefix=1 # 可以去掉product之后转发
- package com.lagou.gateway;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.GlobalFilter;
- import org.springframework.core.Ordered;
- import org.springframework.core.io.buffer.DataBuffer;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.server.reactive.ServerHttpRequest;
- import org.springframework.http.server.reactive.ServerHttpResponse;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * 定义全局过滤器,会对所有路由生效
- */
- @Slf4j
- @Component // 让容器扫描到,等同于注册了
- public class BlackListFilter implements GlobalFilter, Ordered {
- // 模拟黑名单(实际可以去数据库或者redis中查询)
- private static List
blackList = new ArrayList<>(); - static {
- blackList.add("0:0:0:0:0:0:0:1"); // 模拟本机地址
- blackList.add("127.0.0.1");
- }
- /**
- * 过滤器核心方法
- * @param exchange 封装了request和response对象的上下文
- * @param chain 网关过滤器链(包含全局过滤器和单路由过滤器)
- * @return
- */
- @Override
- public Mono
filter(ServerWebExchange exchange, GatewayFilterChain - chain) {
- System.out.println("....BlackListFilter....");
- // 思路:获取客户端ip,判断是否在黑名单中,在的话就拒绝访问,不在的话就放行
- // 从上下文中取出request和response对象
- ServerHttpRequest request = exchange.getRequest();
- ServerHttpResponse response = exchange.getResponse();
- // 从request对象中获取客户端ip
- String clientIp = request.getRemoteAddress().getHostString();
- // 拿着clientIp去黑名单中查询,存在的话就决绝访问
- if(blackList.contains(clientIp)) {
- // 决绝访问,返回
- response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
- log.info("=====>IP:" + clientIp + " 在黑名单中,将被拒绝访问!");
- String data = "Request be denied!";
- DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
- return response.writeWith(Mono.just(wrap));
- }
- // 合法请求,放行,执行后续的过滤器
- return chain.filter(exchange);
- }
- /**
- * 返回值表示当前过滤器的顺序(优先级),数值越小,优先级越高
- * @return
- */
- @Override
- public int getOrder() {
- return 0;
- }
- }
- #配置多个GateWay实例
- upstream gateway {
- server 127.0.0.1:9002;
- server 127.0.0.1:9003;
- }
- location / {
- proxy_pass http://gateway;
- }
- "1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
- http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>lagou-parentartifactId>
- <groupId>com.lagougroupId>
- <version>1.0-SNAPSHOTversion>
- parent>
- <modelVersion>4.0.0modelVersion>
- <artifactId>lagou-cloud-configartifactId>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-config-serverartifactId>
- dependency>
- dependencies>
- project>
- package com.lagou.config;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- import org.springframework.cloud.config.server.EnableConfigServer;
- import java.io.ObjectInputFilter;
- @SpringBootApplication
- @EnableConfigServer // 开启配置服务器功能
- @EnableDiscoveryClient
- public class ConfigApplication {
- public static void main(String[] args) {
- SpringApplication.run(ConfigApplication.class, args);
- }
- }
- server:
- port: 9400
- #注册到Eureka服务中心
- eureka:
- client:
- service-url:
- defaultZone:
- http://LagouCloudEurekaServerA:9200/eureka,http://LagouCloudEurekaServerB:9201/e
- ureka
- instance:
- prefer-ip-address: true
- instance-id: ${spring.cloud.client.ipaddress}:${spring.application.name}:${server.port}:@project.version@
- spring:
- application:
- name: lagou-service-config
- cloud:
- config:
- server:
- git:
- uri: https://github.com/jetwu-do/lagou-config.git #配置git服务地址
- username: jetwu-do #配置git用户名
- password: wu7787879 #配置git密码
- search-paths:
- - lagou-config
- # 读取分支
- label: master
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-config-clientartifactId>
- dependency>
- server:
- port: 9100 # 后期该微服务多实例,端口从9100递增(10个以内)
- Spring:
- application:
- name: lagou-service-page
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/lagou?
- useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
- username: root
- password: wu7787879
- cloud:
- config:
- #config客户端配置,和ConfigServer通信,并告知ConfigServer希望获取的配置信息在哪个文
- 件中
- name: application
- profile: dev #后缀名称
- label: master #分支名称
- uri: http://localhost:9400 #ConfigServer配置中心地址
- package com.lagou.page.controller;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @RequestMapping("/config")
- public class ConfigClientController {
- @Value("${mysql.user}")
- private String mysqlUser;
- @Value("${person.name}")
- private String personName;
- @RequestMapping("/remote")
- public String findRemoteConfig() {
- return mysqlUser + " " + personName;
- }
- }
- management:
- endpoints:
- web:
- exposure:
- include: refresh
- #也可以暴露所有的端口
- management:
- endpoints:
- web:
- exposure:
- include: "*"
- package com.lagou.page.controller;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.cloud.context.config.annotation.RefreshScope;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @RequestMapping("/config")
- @RefreshScope //手动刷新
- public class ConfigClientController {
- @Value("${mysql.user}")
- private String mysqlUser;
- @Value("${person.name}")
- private String personName;
- @RequestMapping("/remote")
- public String findRemoteConfig() {
- return mysqlUser + " " + personName;
- }
- }
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-bus-amqpartifactId>
- dependency>
- spring:
- rabbitmq:
- host: 192.169.200.128
- port: 5672
- username: guest
- password: guest
- management:
- endpoints:
- web:
- exposure:
- include: bus-refresh
- #建议暴露所有的端口
- management:
- endpoints:
- web:
- exposure:
- include: "*"

- linux/mac:sh startup.sh -m standalone
- windows:cmd startup.cmd
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-dependenciesartifactId>
- <version>Greenwich.RELEASEversion>
- <type>pomtype>
- <scope>importscope>
- dependency>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-alibaba-dependenciesartifactId>
- <version>2.1.0.RELEASEversion>
- <type>pomtype>
- <scope>importscope>
- dependency>
- dependencies>
- dependencyManagement>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848 #nacos server 地址

Namespace:命名空间,对不同的环境进行隔离,比如隔离开发环境、测试环境和生产环境
|
概念
|
描述
|
|
Namespace
|
代表不同的环境,如开发
dev
、测试
test
、生产环境
prod
|
|
Group
|
代表某项目,比如拉勾云项目
|
|
Service
|
某个项目中具体
xxx
服务
|
|
DataId
|
某个项目中具体的
xxx
配置文件
|

- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
- dependency>
${prefix}-${spring.profile.active}.${file-extension}
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- config:
- server-addr: 127.0.0.1:8848
- namespace: 26ae1708-28de-4f63-8005-480c48ed6510 #命名空间的ID
- group: DEFAULT_GROUP #如果使用的默认分组,可以不设置
- file-extension: yaml
- package com.lagou.page.controller;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.cloud.context.config.annotation.RefreshScope;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @RequestMapping("/config")
- @RefreshScope //自动刷新
- public class ConfigClientController {
- @Value("${lagou.message}")
- private String message;
- @Value("${database.type}")
- private String dbType;
- @RequestMapping("/remote")
- public String findRemoteConfig() {
- return message + " " + dbType;
- }
- }
- # nacos配置
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- # nacos config 配置
- config:
- server-addr: 127.0.0.1:8848
- # 锁定server端的配置文件(读取它的配置项)
- namespace: 07137f0a-bf66-424b-b910-20ece612395a # 命名空间id
- group: DEFAULT_GROUP # 默认分组就是DEFAULT_GROUP,如果使用默认分组可以不配置
- file-extension: yaml #默认properties
- # 根据规则拼接出来的dataId效果:lagou-service-page.yaml
- ext-config[0]:
- data-id: abc.yaml
- group: DEFAULT_GROUP
- refresh: true #开启扩展dataId的动态刷新
- ext-config[1]:
- data-id: def.yaml
- group: DEFAULT_GROUP
- refresh: true #开启扩展dataId的动态刷新
Sentinel 的开源生态:


- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
- dependency>
- server:
- port: 9101 # 后期该微服务多实例,端口从9100递增(10个以内)
- Spring:
- #解决bean重复注册问题
- main:
- allow-bean-definition-overriding: true
- application:
- name: lagou-service-page
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/lagou?
- useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
- username: root
- password: wu7787879
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- config:
- server-addr: 127.0.0.1:8848
- namespace: 26ae1708-28de-4f63-8005-480c48ed6510 #命名空间的ID
- group: DEFAULT_GROUP #如果使用的默认分组,可以不设置
- file-extension: yaml
- #sentinel配置
- sentinel:
- transport:
- dashboard: 127.0.0.1:8080
- port: 8719
- # springboot中暴露健康检查等断点接口
- management:
- endpoints:
- web:
- exposure:
- include: "*"
- # 暴露健康接口的细节
- endpoint:
- health:
- show-details: always
2.4 Sentinel 关键概念
|
概
念
名
称
|
概念描述
|
|
资源
|
它可以是
Java
应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用
的其它应用提供的服务,甚至可以是一段代码。
我们请求的
API
接口就是资源
|
|
规则
|
围绕资源的实时状态设定的规则,可以包括流量控制规则、熔断降级规则以及系统保护规
则。所有规则可以动态实时调整。
|
- package com.lagou.edu.controller;
- import com.lagou.edu.controller.service.ResumeServiceFeignClient;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @RequestMapping("/user")
- public class UserController {
- /**
- * 用户注册接口
- * @return
- */
- @GetMapping("/register")
- public String register() {
- System.out.println("Register success!");
- return "Register success!";
- }
- /**
- * 验证注册身份证接口(需要调用公安户籍资源)
- * @return
- */
- @GetMapping("/validateID")
- public String validateID() {
- System.out.println("validateID");
- return "ValidateID success!";
- }
- }
machine-root/ \/ \Entrance1 Entrance2/ \/ \DefaultNode(nodeA) DefaultNode(nodeA)



异常数