[!NOTE]
本篇内容需要在上一篇的基础上进行。
请找到上一篇的项目代码,本篇在上一篇的源代码上进行编写。
本系列教程目录:https://laisc7301.github.io/blog/2024/01/29/202401290001SpringBoot%E7%B3%BB%E5%88%97%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/
打开上一个模块的源代码(my-consumer-feign),我们继续进行。
整个项目的文件结构如下图所示:
找到pom.xml文件,在<dependencies>标签里添加:
1 2 3 4 5
| <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>
|
找到application.yml,在里面添加:
1 2 3
| feign: sentinel: enabled: true
|
其它文件的源代码:
FeignServiceFallback.java
1 2 3 4 5 6 7 8 9 10 11 12 13
| package org.laisc.consumer.feign.service.fallback;
import org.laisc.consumer.feign.service.FeignService; import org.springframework.stereotype.Component;
@Component public class FeignServiceFallback implements FeignService {
@Override public String test(String message) { return "test fallback"; } }
|
FeignService.java
修改@FeignClient注解,最终变成下面这样:
1 2 3 4 5 6 7 8 9 10 11 12
| package org.laisc.consumer.feign.service;
import org.laisc.consumer.feign.service.fallback.FeignServiceFallback; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "my-provider", fallback = FeignServiceFallback.class) public interface FeignService { @GetMapping(value = "/test/{message}") String test(@PathVariable("message") String message); }
|
现在,关闭所有服务,只打开ConsumerFeignApplication
,访问 http://localhost:9092/test/hi ,你就会看到:
test fallback
项目源代码下载:https://pan.baidu.com/s/1_g7WWmJCxtHVIW-UdGVqHQ?pwd=lnrk
上一篇:Spring Cloud Alibaba创建服务消费者Feign(负载均衡):https://laisc7301.github.io/blog/2024/01/28/202401280000SpringCloudAlibaba%E5%88%9B%E5%BB%BA%E6%9C%8D%E5%8A%A1%E6%B6%88%E8%B4%B9%E8%80%85Feign(%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1)/