学习笔记~~摸鱼时间~~
对于服务的调用,除了RestTemplate还可以使用OpenFeign,当然Feign已经停更了。
在这里我创建了两个服务提供模块(cloud-provider-payment8001\cloud-provider-payment8002),分别注册到了eureka上
首先引入OpenFeign的pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.9.RELEASE</version>
</dependency>
yml文件
server:
port: 80
eureka:
client:
#false表示不向服务端注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
fetch-registry: true
service-url:
#设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
在需要调用服务的模块中创建启动类、service的接口和controller类
启动类中要加上@EnableFeignClients注解
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80
{
public static void main(String[] args)
{
SpringApplication.run(OrderFeignMain80.class,args);
}
}
然后就是接口和controller类的编写
PaymentFeignService接口中添加注解@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
value的值就是之前在eureka上注册服务的名字
@GetMapping(value = "/better/payment/get/{id}")这个路径要和被调用服务的Mapping路径一致
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService
{
@GetMapping(value = "/better/payment/get/{id}")
CommonResult getPaymentById(@PathVariable("id") Integer id);
}
controller类直接调用service的接口
@RestController
@Slf4j
public class PaymentController
{
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Integer id)
{
CommonResult payment = paymentFeignService.getPaymentById(id);
return payment;
}
}
写好了测试一下
(OpenFeign也自带了轮询的调用方式)
相对于RestTemplate个人感觉OpenFeign更符合自己的编程习惯。