整个项目请看gitee:天山雪豹/spring-cloud
sentinel的安装和项目集成:Sentinel的安装和微服务的集成_有一种信仰叫海阔天空-CSDN博客
相关项目Ribbon:cloudalibaba-provider-payment9003,cloudalibaba-provider-payment9004
Feign:cloudalibaba-consumer-nacos-order84
nacos的配置安装请到:SpringCloud-Nacos的搭建使用_有一种信仰叫海阔天空-CSDN博客_springcloud集成nacos搭建查看
Ribbon熔断
服务提供者9003,9004
1、新建cloudalibaba-provider-payment9003(9004下同)
<!-- alibaba nacos 服务端 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 引入api 公共包 -->
<dependency>
<groupId>org.xwb.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、yml配置
server:
port: 9002
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
3、主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain9002.class, args);
}
}
4、controller
@RestController
public class PaymentController {
@Value("\${server.port}")
private String serverPort;
public static HashMap<Long, Payment> hashMap = new HashMap<>();
static {
hashMap.put(1l, new Payment(1L, "210374208734KJEWFKW0U20sklfw0uor023u4"));
hashMap.put(2l, new Payment(2L, "3498hofwsefhls93984rfhseohf2890343rwe"));
hashMap.put(3l, new Payment(3L, "09snkjdfhjoiwhefdsnfjkhweo5235wefhwee"));
}
@GetMapping("/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id) {
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult<>(200, "from mysql,serverPort" + serverPort, payment);
return result;
}
}
服务消费者cloudalibaba-consumer-nacos-order84
1、pom.xml
<!-- alibaba sentinel -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- alibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- alibaba nacos sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2、yml
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
# 默认8719端口,假如被占用会自动从8719开始一次+1循环,直到找到未被占用的端口
port: 8719
# 消费者将要去访问的服务名称(注册进nacos的服务提供者名称)
service-url:
nacos-user-service: http://nacos-payment-provider
3、主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
4、负载均衡
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getLoadBalanced() {
return new RestTemplate();
}
}
5、controller
@Slf4j
@RestController
public class CirleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback")
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
}
return result;
}
public CommonResult<Payment> fallback(BlockException blockException) {
return new CommonResult<Payment>(444, "", null);
}
}
测试
启动顺序nacos,sentinel,9003,9004,最后启动调用方84
1、@SentinelResource(value = "fallback", fallback = "handlerFallback") fallback
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback", fallback = "handlerFallback")//只负责业务异常
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
}
return result;
}
public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
Payment payment = new Payment(id, null);
return new CommonResult(444, "兜底异常handlerFallback,exception内容" + e.getMessage(), payment);
}
测试结果
2、测试@SentinelResource(value = "fallback", blockHandler = "handlerFallback")blockHandler 。blockHandler只负责sentinel控制台的配置
@SentinelResource(value = "fallback", blockHandler = "blockHandler")//blockHandler只负责sentinel控制台的配置
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
}
return result;
}
public CommonResult blockHandler(@PathVariable("id")Long id, BlockException blockException){
Payment payment=new Payment(id,null);
return new CommonResult(445,"blockHandler-sentinel限流,无此流水,blockException:"+blockException.getMessage(),payment);
}
测试结果(第一次异常页面,连续一秒内刷新超过2次,出现sentinel的限流规则)
3、如果fallback和blockHandler都配置了,该怎么执行
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handlerFallback", blockHandler = "blockHandler")
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
}
return result;
}
public CommonResult blockHandler(@PathVariable("id")Long id, BlockException blockException){
Payment payment=new Payment(id,null);
return new CommonResult(445,"blockHandler-sentinel限流,无此流水,blockException:"+blockException.getMessage(),payment);
}
public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
Payment payment = new Payment(id, null);
return new CommonResult(444, "兜底异常handlerFallback,exception内容" + e.getMessage(), payment);
}
结果(刷新浏览器1秒超过2次)
若blockHandler和fallback都配置了,则被限流降级而抛出BlockException时只会进入blockHandler处理逻辑
exceptionsToIgnore
Fenign熔断
修改cloudalibaba-consumer-nacos-order84使用feign调用
1、pom.xml
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、aplication.yml
# 激活sentinel对feign的支持
feign:
sentinel:
enabled: true
3、开启对feign的支持@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
4、openFeign提供接口调用OpenClient
@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping("/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id);
}
@Component
public class PaymentFallbackService implements PaymentService {
@Override
public CommonResult paymentSQL(Long id) {
return new CommonResult<Payment>(4444,"",new Payment(id,"errorSerial"));
}
}
测试
启动nacos,sentinel,9003,9004,84,访问一下地址
1、 http://localhost:84/consumer/paymentSQL/1 访问结果(正常访问)
2、此时关闭9003,或者9004,再次刷新访问如下效果
会发现调用失败,服务自动降级