SpringCloudAlibaba-16-sentinel整合feign实现服务调用

前言

使用sentinel实现服务间的调用,sentinel在这里面作为了是流量防护组件。他结合openfeign实现了服务降级等作用。 以下我们创建结合sentinel和feign的创建2个应用,服务消费方,服务提供方。

内容

服务提供方:provider创建

  1. 1.创建spring项目
  2. 2.引入cloud依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!--依赖版本定义-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
```
4. 4.使用sentinel、openfeign、discovery


com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery


com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel


org.springframework.cloud
spring-cloud-starter-openfeign

1
2
3
5. 5.我们是服务提供方,我们书写一个接口

@RestController
public class DemoController {
@GetMapping(“/feign”)
public String feign(){
return “hello sentinel feign”;
}
}

1
2
6. 6.启动类添加注解

@SpringCloudApplication
public class SentinelFeignProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SentinelFeignProviderApplication.class, args);
}
}

1
2
7. 7.添加配置文件application.yml

server:
port: 18082
spring:
application:
name: sentinel-feign-provider
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848

1
2
3
4
5
6
7
#### 服务消费方:consumer创建
我们复制sentinel-feign-provider修改成 sentinel-feign-consumer
启动类上添加注解:@EnableFeignClients
1. 1.创建feign客户端

@FeignClient(value = “sentinel-feign-provider”,fallback =DemoFeignClientFallback.class)
public interface DemoFeginClient {
@GetMapping(“/feign”)
String feign();
}

1
2
3
2. 2.创建服务降级实现类

@Component
public class DemoFeignClientFallback implements DemoFeginClient {
@Override
public String feign() {
return “error”;
}
}

1
2
3. 3.创建consumer的测试请求类:

@RestController
public class DemoController {
@Autowired
private DemoFeginClient demoFeginClient;
@GetMapping(“/hello”)
public String feign(){
return demoFeginClient.feign();
}
}
```

测试:
http://localhost:18083/hello
结果:
hello sentinel feign

毕业于<br>相信技术可以改变人与人之间的生活<br>码农一枚