長沙做網(wǎng)站湖南微聯(lián)訊點靠譜百度廣告搜索推廣
目錄地址:
SpringCloudAlibaba整合-CSDN博客
這里只關(guān)注代碼部分,至于sentinel服務(wù)UI的實用,后面可以補上
這里做一個改造:
因為sentinel可以和openfeign結(jié)合使用,為微服務(wù)做熔斷降級;
為了方便微服務(wù)之間的調(diào)用,把遠程調(diào)用接口移動到api模塊;
所以把order中的openfeign和loadbalancer依賴,放到api的pom中,并且把order中Remote接口,移動到api中;后續(xù)order只需要引入api的依賴,調(diào)用api中的接口即可
1.在api中引入sentinel和openfeign
<!--openfeign-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency><!--loadbalancer-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency><!--sentinel-->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2.把接口從order轉(zhuǎn)移到api,并修改
@FeignClient(name="my-user", fallbackFactory = UserServiceFactory.class)
public interface RemoteUserService {@RequestMapping("/user/listAll")public List<User> listAll();@GetMapping("/user/getById")public User getById(@RequestParam("id") Integer id);
}
api模塊,添加UserServiceFactory類
@Component
public class UserServiceFactory implements FallbackFactory<RemoteUserService> {@Overridepublic RemoteUserService create(Throwable cause) {return new RemoteUserService() {@Overridepublic List<User> listAll() {return null;}@Overridepublic User getById(Integer id) {System.out.println("user服務(wù)異常");return null;}};}
}
3.注意要把UserServiceFactory放到META-INF/spring.factories文件中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.test.api.remote.fallbackFactory.UserServiceFactory,\
com.test.api.remote.fallbackFactory.ProductServiceFactory
4.order引入api依賴,并在啟動類添加注解,掃描feignClient接口
@EnableFeignClients(basePackages = {"com.test.api.remote"})
5.order的配置文件添加
feign:sentinel:enabled: true
6.重啟服務(wù),訪問接口,正常訪問
此時停止user服務(wù),再次訪問order接口,返回null,后臺日志打印“user服務(wù)異常”