SpringCloud常用组件

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

SpringCloud常⽤组件
Spring Cloud Alibaba
Spring Cloud Alibaba 致⼒于提供微服务开发的⼀站式解决⽅案。

此项⽬包含开发分布式应⽤微服务的必需组件,⽅便开发者通过 Spring Cloud 编程模型轻松使⽤这些组件来开发分布式应⽤服务。

引⼊依赖,在dependencyManagement中添加如下配置。

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Nacos 服务注册与发现
Nacos 是阿⾥巴巴开源的⼀个更易于构建云原⽣应⽤的动态服务发现、配置管理和服务管理平台。

⾸先需要获取 Nacos Server,
修改 pom.xml ⽂件,引⼊ Nacos Discovery Starter。

<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
在配置⽂件中配置 Nacos Server 地址
server:
port: 8082
spring:
application:
name: service-provider
cloud:
nacos:
server-addr: 127.0.0.1:8848
使⽤ @EnableDiscoveryClient 注解开启服务注册与发现功能
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
Nacos 分布式配置管理
⾸先,修改 pom.xml ⽂件,引⼊ Nacos Config Starter。

<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
在应⽤的/src/main/resources/bootstrap.yml配置⽂件中配置 Nacos Config 元数据
spring:
application:
name: service-provider
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
namespace: d1c63875-be0c-46db-81d5-bd037567f9c1
file-extension: yaml
完成上述两步后,应⽤会从 Nacos Config 中获取相应的配置,并添加在 Spring Environment 的 PropertySources 中。

这⾥我们使⽤注解来将对应的配置注⼊到 SampleController 的 userName 和 age 字段,并添加打开动态刷新功能
@RefreshScope
class SampleController {
@Value("${}")
String userName;
@Value("${user.age}")
int age;
}
在Nacos控制台的配置列表中添加配置,Data ID: service-provider.yaml,Group: DEFAULT_GROUP,内容如下
user:
name: orange
age: 23
OpenFeign 服务调⽤
OpenFeign 是Spring Cloud 的组件,所以要加⼊spring cloud 的依赖管理
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Nacos Discovery Starter 默认集成了 Ribbon ,所以对于使⽤了 Ribbon 做负载均衡的组件,可以直接使⽤ Nacos 的服务发现。

⾸先,修改 pom.xml ⽂件,引⼊ OpenFeign Starter。

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
使⽤注解@EnableFeignClients开启服务调⽤
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
FeignClient 已经默认集成了 Ribbon ,此处演⽰如何配置⼀个 FeignClient。

@FeignClient(name = "service-provider")
public interface EchoService {
@GetMapping(value = "/echo/{str}")
String echo(@PathVariable("str") String str);
}
Gateway ⽹关
简单使⽤
修改 pom.xml ⽂件,引⼊ Sentinel Starter
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
⽹关配置
server:
port: 8080
spring:
application:
name: service-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
routes:
- id: service-provider
uri: lb://service-provider
predicates:
- Path=/provider/**
- id: service-consumer
uri: lb://service-consumer
predicates:
- Path=/consumer/**
Sentinel 流量控制、熔断降级
随着微服务的流⾏,服务和服务之间的稳定性变得越来越重要。

Sentinel 以流量为切⼊点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

如何在Spring Cloud Alibaba中使⽤Sentinel
1. ⾸先下载 Sentinel 控制台 jar 包:
启动Sentinel控制台
java -jar sentinel-dashboard-1.8.1.jar --server.port=9090
访问localhost:9090,默认⽤户名密码都是sentinel
2. 修改 pom.xml ⽂件,引⼊ Sentinel Starter
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
3. 配置 Sentinel 控制台地址信息
application.yml
spring:
cloud:
sentinel:
transport:
port: 8719
dashboard: localhost:9090
这⾥的spring.cloud.sentinel.transport.port端⼝配置会在应⽤对应的机器上启动⼀个 Http Server,该 Server 会与 Sentinel 控制台做交互。

⽐如Sentinel 控制台添加了⼀个限流规则,会把规则数据 push 给这个 Http Server 接收,Http Server 再将规则注册到 Sentinel 中。

sentinel 流量控制
访问这个加上流控规则的路径时,每秒⼤于⼀个请求就会返回失败信息
这个时sentinel默认的返回信息,可以⾃定返回信息
@Configuration
public class SentinelConfig {
@Bean
public BlockExceptionHandler blockExceptionHandler() {
return new BlockExceptionHandler() {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
httpServletResponse.setContentType("application/json;charset=utf-8");
ResponseData responseData = new ResponseData(5001, "活动⽕爆,请稍后再试");
String s = new ObjectMapper().writeValueAsString(responseData);
httpServletResponse.getWriter().write(s);
}
};
}
}
Sentinel ⽀持 Endpoint
在使⽤ Endpoint 特性之前需要在 Maven 中添加 spring-boot-starter-actuator 依赖,并在配置中允许 Endpoints 的访问。

Spring Boot 1.x 中添加配置management.security.enabled=false。

暴露的 endpoint 路径为/sentinel
Spring Boot 2.x 中添加配置management.endpoints.web.exposure.include=*。

暴露的 endpoint 路径为/actuator/sentinel
Sentinel Endpoint ⾥暴露的信息⾮常有⽤。

包括当前应⽤的所有规则信息、⽇志⽬录、当前实例的 IP,Sentinel Dashboard 地址,Block Page,应⽤与 Sentinel Dashboard 的⼼跳频率等等信息。

Sentinel⽀持Feign服务熔断
Sentinel 适配了 Feign 组件。

如果想使⽤,除了引⼊spring-cloud-starter-alibaba-sentinel,只需要在配置⽂件打开 Sentinel 对 Feign 的⽀持feign:
sentinel:
enabled: true
@FeignClient(value = "service-provider",fallback = ProviderOuterServiceFallback.class)
public interface ProviderOuterService {
@GetMapping("provider/hello/{name}")
String hello(@PathVariable String name);
}
@Component
public class ProviderOuterServiceFallback implements ProviderOuterService {
@Override
public String hello(String name) {
return "系统错误";
}
}
Sentinel-Gateway⽹关限流
从 1.6.0 版本开始,Sentinel 提供了 Spring Cloud Gateway 的适配模块,可以提供两种资源维度的限流:
route 维度:即在 Spring 配置⽂件中配置的路由条⽬,资源名为对应的 routeId
⾃定义 API 维度:⽤户可以利⽤ Sentinel 提供的 API 来⾃定义⼀些 API 分组
使⽤时在⽹关服务添加sentinel适配gateway的依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
来个使⽤案例,所有的请求都会经过⽹关服务,限制每个IP每秒最多能请求三次;
API管理 > 新增API分组
匹配串/**表⽰所有的请求
流控规则 > 新增⽹关流控规则
当单个相同的IP每秒请求次数超过3次就会返回失败信息
这个是Sentinel默认的返回信息,可以⾃定义
@Configuration
public class SentinelGatewayConfig {
@Bean
public BlockRequestHandler blockRequestHandler() {
return new BlockRequestHandler() {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) { ResponseData responseData = new ResponseData(4001, "请稍后再试");
String res = null;
try {
res = new ObjectMapper().writeValueAsString(responseData);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(res), String.class);
return body;
}
};
}
}。

相关文档
最新文档