Spring Cloud Alibaba 的学习之feign篇
Posted faramita
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Cloud Alibaba 的学习之feign篇相关的知识,希望对你有一定的参考价值。
是什么?
Feign 是一个声明式的伪 HTTP 客户端,它使得写 HTTP 客户端变得更简单
为什么?
使用 Feign,只需要创建一个接口并注解。它具有可插拔的注解特性。Feign 支持可插拔的编码器和解码器。Feign 默认集成了 Ribbon,Nacos 也很好的兼容了 Feign,默认实现了负载均衡的效果
怎么做
提供者:
yml:
spring:
application:
name: puzzle-provider
cloud:
nacos:
discovery:
server-addr: 192.168.233.150:8848
server:
port: 11000
management:
endpoints:
web:
application:
@SpringBootApplication
@EnableDiscoveryClient
public class PuzzleProviderApplication
public static void main(String[] args)
SpringApplication.run(PuzzleProviderApplication.class, args);
service:
@Service
public class InitPuzzleServiceImpl implements InitPuzzleService
@Override
public List initPuzzle()
List list= Arrays.asList("1", "2", "3","4","5","6","7","8","0");
return list;
controller
@RestController
public class InitPuzzleController
@Autowired
private InitPuzzleService initPuzzleService;
@GetMapping(value = "init")
public List initPuzzle()
return initPuzzleService.initPuzzle();
消费者:
yml:
spring:
application:
name: consumer-reset
cloud:
nacos:
discovery:
server-addr: 192.168.233.150:8848
feign:
sentinel:
enabled: true
server:
port: 12000
management:
endpoints:
web:
exposure:
include: "*"
POM
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Application(主要添加EnableFeignClients)
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class PuzzleResetApplication
public static void main(String[] args)
SpringApplication.run(PuzzleResetApplication.class, args);
Service(@FeignClient("服务名") 注解来指定调用哪个服务)
@FeignClient(value = "puzzle-provider")
public interface ResetService
@GetMapping(value = "init")
List initPuzzle();
Controller
@RestController
public class ResetController
@Autowired
private ResetService resetService;
@GetMapping("/reset")
public List resetPuzzle()
List list = resetService.initPuzzle();
Collections.shuffle(list);
return list;
配置负载均衡
修改 service-provider 服务的端口号如 11000,并启动多个实例,IDEA 中依次点击 Run -> Edit Configurations 并勾选 Allow parallel run 以允许 IDEA 多实例运行项目
以上是关于Spring Cloud Alibaba 的学习之feign篇的主要内容,如果未能解决你的问题,请参考以下文章
Spring Cloud Alibaba全家桶——Spring Cloud Alibaba介绍
Spring Cloud Alibaba系列教程——Spring Cloud Alibaba开篇
spring boot 整合spring cloud alibaba
spring boot 整合spring cloud alibaba