这里不做过多理论说明,直接进入实战操作。
第一章:Nacos Discovery——服务发现与注册管理
- <repositories>
- <repository>
- <id>Localhostid>
- <name>Localhostname>
- <url>file://xxx/Repositoryurl>
- repository>
- <repository>
- <id>alimavenid>
- <name>aliyun mavenname>
- <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
- <releases>
- <enabled>trueenabled>
- releases>
- <snapshots>
- <enabled>falseenabled>
- snapshots>
- repository>
- repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>alimavenid>
- <name>aliyun mavenname>
- <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
- <releases>
- <enabled>trueenabled>
- releases>
- <snapshots>
- <enabled>falseenabled>
- snapshots>
- pluginRepository>
- <pluginRepository>
- <id>Localhostid>
- <name>Localhostname>
- <url>file://xxx/Repositoryurl>
- pluginRepository>
- pluginRepositories>
- <properties>
- <spring-cloud.version>2021.0.1spring-cloud.version>
- <spring-cloud-alibaba.version>2021.0.1.0spring-cloud-alibaba.version>
- properties>
-
- <parent>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-buildartifactId>
- <version>3.1.1version>
- <relativePath/>
- parent>
-
- <dependencies>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-bootstrapartifactId>
- dependency>
- dependencies>
-
- <dependencyManagement>
- <dependencies>
-
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-dependenciesartifactId>
- <version>${spring-boot.version}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>
-
- <pluginRepositories>
- <pluginRepository>
- <id>aliyun-pluginid>
- <url>https://maven.aliyun.com/repository/publicurl>
- <releases>
- <enabled>trueenabled>
- releases>
- <snapshots>
- <enabled>falseenabled>
- snapshots>
- pluginRepository>
- pluginRepositories>
- <repositories>
-
- <repository>
- <id>aliyunid>
- <name>aliyunname>
- <url>http://maven.aliyun.com/nexus/content/groups/publicurl>
- repository>
- repositories>
- 3. Nacos client provider创建。
- a) 创建alibaba-spring-cloud-provider子工程,添加依赖。
- <parent>
- <groupId>com.cloudgroupId>
- <artifactId>alibaba-spring-cloudartifactId>
- <version>1.0-SNAPSHOTversion>
- <relativePath>../pom.xmlrelativePath>
- parent>
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
-
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
- dependencies>
- server:
- port: 18080
-
- spring:
- application:
- name: provider-service
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- enabled: true
- username: nacos
- password: nacos
-
- management:
- endpoints:
- web:
- exposure:
- include: "*"
- endpoint:
- health:
- show-details: always
- package com.cloud.controller;
-
- import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.bind.annotation.*;
-
- import javax.annotation.Resource;
- import java.util.Map;
-
- /**
- * 项目名称: provider
- * 包名称: com.cloud.controller
- * 类名称: ProviderController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/9 14:45
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class ProviderController {
-
- @GetMapping("/echo/{string}")
- public String echo(@PathVariable String string) {
- return "hello Nacos Discovery " + string;
- }
-
- }
- <parent>
- <groupId>com.cloudgroupId>
- <artifactId>alibaba-spring-cloudartifactId>
- <version>1.0-SNAPSHOTversion>
- <relativePath>../pom.xmlrelativePath>
- parent>
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-loadbalancerartifactId>
- dependency>
- dependencies>
- server:
- port: 18011
-
- spring:
- application:
- name: consumer-service
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- enabled: true
- username: nacos
- password: nacos
- loadbalancer.nacos.enabled: true
-
- management:
- endpoints:
- web:
- exposure:
- include: "*"
- endpoint:
- health:
- show-details: always
- package com.cloud.controller;
-
- import com.cloud.service.EchoService;
- 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;
-
- import javax.annotation.Resource;
-
- /**
- * 项目名称: consumer
- * 包名称: com.cloud.controller
- * 类名称: ConsumerController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/11 9:34
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class ConsumerController {
-
- @Resource
- private RestTemplate restTemplate;
-
- @RequestMapping("/echo/{string}")
- public String echo(@PathVariable String string) {
- return restTemplate.getForObject("http://provider-service/echo/{string}", String.class, string);
- }
-
- }
- package com.cloud.configurer;
-
- import org.springframework.cloud.client.loadbalancer.LoadBalanced;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.client.RestTemplate;
-
- /**
- * 项目名称: consumer
- * 包名称: com.cloud.configurer
- * 类名称: RestTemplateConfig
- * 类描述: RestTemplate配置
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/11 9:32
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @Configuration
- public class RestTemplateConfig {
-
- @Bean
- @LoadBalanced
- public RestTemplate createRestTemplate(){
- return new RestTemplate();
- }
-
- }
第二章:Nacos OpenFeign——使用openFeign实现服务调用
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
- package com.cloud.service;
-
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestParam;
-
- @FeignClient(name = "provider-service",fallback = EchoServiceFallback.class)
- public interface EchoService {
-
- @GetMapping("/echo/{str}")
- String echo(@PathVariable("str") String str);
-
- @GetMapping("/notFound")
- String notFound();
-
- }
- package com.cloud.service;
-
- import org.springframework.stereotype.Component;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestParam;
-
- /**
- * 项目名称: consumer
- * 包名称: com.cloud.service
- * 类名称: EchoServiceFallback
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/11 9:53
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @Component
- public class EchoServiceFallback implements EchoService{
- @Override
- public String echo(@PathVariable("str") String str) {
- return "echo fallback";
- }
-
- @Override
- public String notFound() {
- return "notFound fallback";
- }
- }
- package com.cloud.controller;
-
- import com.cloud.service.EchoService;
- 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;
-
- import javax.annotation.Resource;
-
- /**
- * 项目名称: consumer
- * 包名称: com.cloud.controller
- * 类名称: ConsumerController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/11 9:34
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class ConsumerController {
-
- @Resource
- private RestTemplate restTemplate;
- @Resource
- private EchoService echoService;
-
- @RequestMapping("/echo/{string}")
- public String echo(@PathVariable String string) {
- return restTemplate.getForObject("http://provider-service/echo/{string}", String.class, string);
- }
-
- @RequestMapping("/echoForFeign/{string}")
- public String echoForFeign(@PathVariable String string) {
- return echoService.echo(string);
- }
-
- @RequestMapping("/notFound")
- public String notFound(){
- return echoService.notFound();
- }
-
- }
第三章:Nacos config——配置管理
- <parent>
- <groupId>com.cloudgroupId>
- <artifactId>alibaba-spring-cloudartifactId>
- <version>1.0-SNAPSHOTversion>
- <relativePath>../pom.xmlrelativePath>
- parent>
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-bootstrapartifactId>
- dependency>
- dependencies>
- server:
- port: 18082
-
- spring:
- application:
- name: nacos-config
- cloud:
- nacos:
- config:
- server-addr: 127.0.0.1:8848
- file-extension: yml
- #优先级shared-configs < extension-configs < ${spring.application.name}-${spring-profiles-active}.${file-extension}
- shared-configs:
- - data-id: nacos-config-shared1.yml
- group: SHARED1_GROUP
- refresh: true
- - data-id: nacos-config-shared2.yml
- group: SHARED1_GROUP
- refresh: false
- extension-configs:
- - data-id: nacos-config-extension1.yml
- group: EXTENSION1_GROUP
- refresh: true
- - data-id: nacos-config-extension2.yml
- group: EXTENSION2_GROUP
- refresh: false
- profiles:
- active: dev
- package com.cloud.controller;
-
- import com.google.common.collect.Maps;
- 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;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * 项目名称: config
- * 包名称: com.cloud.controller
- * 类名称: ConfigController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/11 14:31
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- @RefreshScope
- public class ConfigController {
-
- @Value("${user.name}")
- private String name;
- @Value("${user.age}")
- private String age;
- @Value("${shared1}")
- private String shared1;
- @Value("${shared2}")
- private String shared2;
- @Value("${extension1}")
- private String extension1;
- @Value("${extension2}")
- private String extension2;
-
- @RequestMapping("/configTest")
- public Map configTest() {
- HashMap
- map.put("name", name);
- map.put("age", age);
- map.put("shared1", shared1);
- map.put("shared2", shared2);
- map.put("extension1", extension1);
- map.put("extension2", extension2);
-
- return map;
- }
-
- }
- #nacos-config-dev.yml
- user:
- name: zhihong.zhu
- age: 288
- #nacos-config-extension1.yml
- user:
- name: zhihong.zhu
- age: 288
- extension1: extension11
- #nacos-config-extension2.yml
- user:
- name: zhihong.zhu
- age: 289
- extension2: extension22
- #nacos-config-shared1.yml
- user:
- name: zhihong.zhu
- age: 28
- shared1: shared1
- #nacos-config-shared2.yml
- user:
- name: zhihong.zhu
- age: 28
- shared2: shared2
第四章:Nacos Gateway——API网关
- <parent>
- <groupId>com.cloudgroupId>
- <artifactId>alibaba-spring-cloudartifactId>
- <version>1.0-SNAPSHOTversion>
- <relativePath>../pom.xmlrelativePath>
- parent>
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-gatewayartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
- dependencies>
- server:
- port: 18083
-
- spring:
- application:
- name: nacos-gateway
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- username: nacos
- password: nacos
- gateway:
- discovery:
- locator:
- enabled: true
- routes:
- - id: nacos-route
- uri: lb://provider-service
- predicates:
- - Path=/nacos/**
- filters:
- - StripPrefix=1
-
- management:
- endpoints:
- web:
- exposure:
- include: "*"
- endpoint:
- health:
- show-details: always
第五章:Sentinel——流控、熔断、降级
- <repositories>
- <repository>
- <id>Localhostid>
- <name>Localhostname>
- <url>file://xxx/Repositoryurl>
- repository>
- <repository>
- <id>alimavenid>
- <name>aliyun mavenname>
- <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
- <releases>
- <enabled>trueenabled>
- releases>
- <snapshots>
- <enabled>falseenabled>
- snapshots>
- repository>
- repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>alimavenid>
- <name>aliyun mavenname>
- <url>https://maven.aliyun.com/nexus/content/repositories/central/url>
- <releases>
- <enabled>trueenabled>
- releases>
- <snapshots>
- <enabled>falseenabled>
- snapshots>
- pluginRepository>
- <pluginRepository>
- <id>Localhostid>
- <name>Localhostname>
- <url>file://xxx/Repositoryurl>
- pluginRepository>
- pluginRepositories>
- <parent>
- <groupId>com.cloudgroupId>
- <artifactId>alibaba-spring-cloudartifactId>
- <version>1.0-SNAPSHOTversion>
- <relativePath>../pom.xmlrelativePath>
- parent>
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
- <dependency>
- <groupId>com.alibaba.cspgroupId>
- <artifactId>sentinel-datasource-nacosartifactId>
- 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>com.fasterxml.jackson.dataformatgroupId>
- <artifactId>jackson-dataformat-xmlartifactId>
- dependency>
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-alibaba-sentinel-datasourceartifactId>
- dependency>
- dependencies>
- server:
- port: 18086
-
-
- spring:
- application:
- name: nacos-sentinel
- cloud:
- sentinel:
- transport:
- dashboard: localhost:8868
- eager: true
- web-context-unify: true
- filter:
- enabled: false
- http-method-specify: false
- datasource:
- # ds6:
- # nacos:
- # server-addr: 127.0.0.1:8848
- # username: nacos
- # password: nacos
- # dataId: flowrule.json
- # data-type: json
- # rule-type: flow
- ds1:
- file:
- file: "classpath: flowrule.xml"
- data-type: xml
- rule-type: flow
- ds2:
- file:
- file: "classpath: degraderule.json"
- data-type: json
- rule-type: degrade
- ds3:
- file:
- file: "classpath: authority.json"
- rule-type: authority
- ds4:
- file:
- file: "classpath: system.json"
- rule-type: system
- ds5:
- file:
- file: "classpath: param-flow.json"
- rule-type: param_flow
-
- management:
- endpoints:
- web:
- exposure:
- include: "*"
-
- feign:
- sentinel:
- enabled: true

- package com.cloud.controller;
-
- import com.alibaba.cloud.commons.lang.StringUtils;
- import com.alibaba.csp.sentinel.annotation.SentinelResource;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.client.RestTemplate;
-
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
- import java.util.Arrays;
-
- /**
- * 项目名称: consumer
- * 包名称: com.cloud.controller
- * 类名称: SentinelController {
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/15 14:12
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class SentinelController {
-
- @GetMapping("/test")
- @SentinelResource(value = "test")
- public String test(){
- return "Hello test";
- }
- }
- package com.cloud.configurer;
-
- import com.alibaba.csp.sentinel.slots.block.BlockException;
-
- public final class ExceptionUtil {
-
- private ExceptionUtil() {
- }
-
- public static String blockException(BlockException ex) {
- System.out.println("Oops: " + ex.getClass().getCanonicalName());
- return ex.getClass().getCanonicalName();
- }
-
- }
- package com.cloud.controller;
-
- import com.alibaba.csp.sentinel.annotation.SentinelResource;
- import com.cloud.configurer.ExceptionUtil;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.client.RestTemplate;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.controller
- * 类名称: SentinelController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/12 14:56
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class SentinelController {
-
- @GetMapping("/test")
- @SentinelResource(value = "test",
- blockHandler = "blockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test(){
- return "Hello test";
- }
-
- }
- package com.cloud.configurer;
-
- import com.alibaba.fastjson.serializer.SerializerFeature;
- import com.alibaba.fastjson.support.config.FastJsonConfig;
- import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.http.MediaType;
- import org.springframework.http.converter.HttpMessageConverter;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- import java.nio.charset.Charset;
- import java.util.Arrays;
- import java.util.List;
-
- /**
- * @author yuhuangbin
- */
- @Configuration
- @EnableWebMvc
- public class WebMvcConfiguration implements WebMvcConfigurer {
-
- // 使用阿里 FastJson 作为JSON MessageConverter
- @Override
- public void configureMessageConverters(List
> converters) { - FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
- FastJsonConfig config = new FastJsonConfig();
- config.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, // 集合为null时返回空集合
- SerializerFeature.WriteMapNullValue, // 保留空的字段
- SerializerFeature.WriteDateUseDateFormat,// 使用时间转换
- SerializerFeature.WriteNullStringAsEmpty);//String null -> ""
- // SerializerFeature.WriteNullNumberAsZero//Number null -> 0
- // 按需配置,更多参考FastJson文档
- // config.setParserConfig();
- converter.setFastJsonConfig(config);
- // converter.setDateFormat("yyyy-MM-dd HH:mm:ss");
- converter.setDefaultCharset(Charset.forName("UTF-8"));
- converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
- converters.add(0, converter);
- }
- }
- package com.cloud.controller;
-
- import com.alibaba.cloud.commons.lang.StringUtils;
- import com.alibaba.csp.sentinel.annotation.SentinelResource;
- import com.cloud.configurer.ExceptionUtil;
- import com.cloud.configurer.SentinelFallbackFactory;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.controller
- * 类名称: SentinelController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/12 14:56
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class SentinelController {
-
-
- @GetMapping("/test")
- @SentinelResource(value = "test",
- blockHandler = "blockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test(){
- return "Hello test";
- }
-
-
- @GetMapping("/test2/{p1}")
- @SentinelResource(value = "abc0",
- fallback = "test2Fallback",
- fallbackClass = SentinelFallbackFactory.class)
- public String test2(@PathVariable String p1){
- if (StringUtils.equals("1",p1)){
- throw new RuntimeException("参数为1导致异常");
- }
- return "Hello(你好) test1-"+p1;
- }
-
- }
- package com.cloud.configurer;
-
- import org.springframework.web.bind.annotation.PathVariable;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.configurer
- * 类名称: SentinelFallbackFactory
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/15 14:17
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- public class SentinelFallbackFactory {
-
- public static String test2Fallback(@PathVariable String p1,Throwable throwable) {
- return "触发熔断"+throwable.getMessage();
- }
- }
- package com.cloud.controller;
-
- import com.alibaba.cloud.commons.lang.StringUtils;
- import com.alibaba.csp.sentinel.annotation.SentinelResource;
- import com.cloud.configurer.ExceptionUtil;
- import com.cloud.configurer.SentinelFallbackFactory;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.controller
- * 类名称: SentinelController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/12 14:56
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class SentinelController {
-
- @GetMapping("/test")
- @SentinelResource(value = "test",
- blockHandler = "blockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test(){
- return "Hello test";
- }
-
-
- @GetMapping("/test2/{p1}")
- @SentinelResource(value = "abc0",
- fallback = "test2Fallback",
- fallbackClass = SentinelFallbackFactory.class)
- public String test2(@PathVariable String p1){
- if (StringUtils.equals("1",p1)){
- throw new RuntimeException("参数为1导致异常");
- }
- return "Hello(你好) test1"+p1;
- }
-
- @GetMapping("/test3/{p1}/{p2}")
- @SentinelResource(value = "aa",
- blockHandler = "test3BlockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test3(@PathVariable String p1,@PathVariable String p2){
- return "Hello(你好) test3-p1="+p1+"p2="+p2;
- }
-
- }
- package com.cloud.configurer;
-
- import com.alibaba.csp.sentinel.slots.block.BlockException;
-
- public final class ExceptionUtil {
-
- private ExceptionUtil() {
- }
-
- public static String blockException(BlockException ex) {
- System.out.println("Oops: " + ex.getClass().getCanonicalName());
- return ex.getClass().getCanonicalName();
- }
-
- public static String test3BlockException(String p1,String p2,BlockException ex) {
- System.out.println("Oops: " + ex.getClass().getCanonicalName());
- return ex.getClass().getCanonicalName();
- }
-
- }
- package com.cloud.controller;
-
- import com.alibaba.cloud.commons.lang.StringUtils;
- import com.alibaba.csp.sentinel.annotation.SentinelResource;
- import com.cloud.configurer.ExceptionUtil;
- import com.cloud.configurer.SentinelFallbackFactory;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.controller
- * 类名称: SentinelController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/12 14:56
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class SentinelController {
-
- @GetMapping("/test")
- @SentinelResource(value = "test",
- blockHandler = "blockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test() {
- return "Hello test";
- }
-
-
- @GetMapping("/test2/{p1}")
- @SentinelResource(value = "abc0",
- fallback = "test2Fallback",
- fallbackClass = SentinelFallbackFactory.class)
- public String test2(@PathVariable String p1) {
- if (StringUtils.equals("1", p1)) {
- throw new RuntimeException("参数为1导致异常");
- }
- return "Hello(你好) test1" + p1;
- }
-
- @GetMapping("/test3/{p1}/{p2}")
- @SentinelResource(value = "aa",
- blockHandler = "test3BlockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test3(@PathVariable String p1, @PathVariable String p2) {
- return "Hello(你好) test3-p1=" + p1 + "p2=" + p2;
- }
-
- @GetMapping("/test4")
- @SentinelResource(value = "bad",
- blockHandler = "test4BlockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test4(HttpServletRequest request) {
- return "Hello(你好) test4-p1=" + request.getParameter("p1");
- }
-
- }
- package com.cloud.configurer;
-
- import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
- import org.springframework.stereotype.Component;
-
- import javax.servlet.http.HttpServletRequest;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.configurer
- * 类名称: MyRequestOriginParser
- * 类描述: 自定义来源处理规则
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/15 16:40
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @Component
- public class MyRequestOriginParser implements RequestOriginParser {
-
- @Override
- public String parseOrigin(HttpServletRequest request) {
- return request.getParameter("p1");
- }
-
- }
- package com.cloud.controller;
-
- import com.alibaba.cloud.commons.lang.StringUtils;
- import com.alibaba.csp.sentinel.annotation.SentinelResource;
- import com.cloud.configurer.ExceptionUtil;
- import com.cloud.configurer.SentinelFallbackFactory;
- import com.cloud.service.SentinelService;
- 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.RestController;
-
- import javax.servlet.http.HttpServletRequest;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.controller
- * 类名称: SentinelController
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/12 14:56
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @RestController
- public class SentinelController {
-
- @Autowired
- private SentinelService sentinelService;
-
- @GetMapping("/test")
- @SentinelResource(value = "test",
- blockHandler = "blockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test() {
- return "Hello test";
- }
-
-
- @GetMapping("/test2/{p1}")
- @SentinelResource(value = "abc0",
- fallback = "test2Fallback",
- fallbackClass = SentinelFallbackFactory.class)
- public String test2(@PathVariable String p1) {
- if (StringUtils.equals("1", p1)) {
- throw new RuntimeException("参数为1导致异常");
- }
- return "Hello(你好) test1" + p1;
- }
-
- @GetMapping("/test3/{p1}/{p2}")
- @SentinelResource(value = "aa",
- blockHandler = "test3BlockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test3(@PathVariable String p1, @PathVariable String p2) {
- return "Hello(你好) test3-p1=" + p1 + "p2=" + p2;
- }
-
- @GetMapping("/test4")
- @SentinelResource(value = "bad",
- blockHandler = "test4BlockException",
- blockHandlerClass = ExceptionUtil.class)
- public String test4(HttpServletRequest request) {
- return "Hello(你好) test4-p1=" + request.getParameter("p1");
- }
-
- @GetMapping("/test5/{p1}")
- public String test5(@PathVariable String p1) {
- return sentinelService.echo(p1);
- }
-
- }
- package com.cloud.service;
-
-
- import com.cloud.configurer.FeignFallbackFactory;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
-
- @FeignClient(name = "provider-service",fallbackFactory = FeignFallbackFactory.class)
- public interface SentinelService {
-
- @GetMapping("/echo/{string}")
- String echo(@PathVariable String string);
- }
- package com.cloud.configurer;
-
- import com.cloud.service.SentinelService;
- import org.springframework.cloud.openfeign.FallbackFactory;
- import org.springframework.stereotype.Component;
-
- /**
- * 项目名称: sentinel
- * 包名称: com.cloud.service
- * 类名称: FeignFallbackFactory
- * 类描述:
- * 创建人: zhihong.zhu
- * 创建时间: 2022/8/15 14:17
- * 修改人:
- * 修改时间:
- * 修改备注:
- */
- @Component
- public class FeignFallbackFactory implements FallbackFactory
{ - @Override
- public SentinelService create(Throwable throwable) {
- return new SentinelService() {
- @Override
- public String echo(String str) {
- return throwable.getClass().getCanonicalName();
- }
- };
- }
- }
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-loadbalancerartifactId>
- dependency>
以上为入门实战的一些操作,如有初学者按照上面方式操作发现问题,请留言,看到后会修正解决。
想了解更多建议看相关源码:https://gitee.com/mirrors/Spring-Cloud-Alibaba/repository/archive/2021.0.1.0