上一节的84项目使用rabbion来调用服务的,也就是
@Resource
private RestTemplate restTemplate;
接下来学习下用feign,feign组件一般用于消费侧。
具体的配置上篇其实全部配置完了,但是这里还是说下主要配什么
org.springframework.cloud
spring-cloud-starter-openfeign
application.yml,一定要开启激活
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-payment-provider
#对Feign的支持
feign:
sentinel:
enabled: true
还有业务接口。这里的GetMapping方法就是9003控制器里的
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService
{
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id);
}
兜底方法 。如果访问 9003项目失败就会走这个。
记得要扫描注入
package com.atguigu.springcloud.alibaba.service;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.stereotype.Component;
/**
* Created by IntelliJ IDEA.
* User: zhuangzibing
* Date: 2020/7/16
*/
@Component
public class PaymentFallbackService implements PaymentService
{
@Override
public CommonResult paymentSQL(Long id)
{
return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
controller
// OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id) {
return paymentService.paymentSQL(id);
}
启动类,添加@EnableFeignClients启动Feign的功能
package com.atguigu.springcloud.alibaba;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84
{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
效果。http://lcoalhost:84/consumer/openfeign/1
测试84调用9003,此时故意关闭9003微服务提供者,看84消费侧自动降级,不会被耗死
前篇讲到节点是临时的,不能保存。或者重启sentinel就没了
主要是sentinel没有内嵌数据库,但是nacos有,所以我们可以配置在nacos里
理论就是
将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上Sentinel上的流控规则持续有效
修改cloudalibaba-sentinel-service8401
pom
com.alibaba.csp
sentinel-datasource-nacos
YML。添加Nacos数据源配置
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
server-addr:localhost:8848
dataid:${spring.application.name}
groupid:DEFAULT_GROUP
data-type:json
rule-type:flow
这里的ID就是application里的name
启动8401后刷新sentinel发现业务规则有了
停止8401再看sentinel
重新启动8401再看sentinel ,多跑下 原来的url,发现自动配置了