- 前言
- 创建项目
- pom.xml
- appliaction.properties
- 启动类
- Cotrolller 接口类
- 启动测试
- 总结& 使用注意事项
上一章Spring Cloud项目中Nacos作为注册中心 在使用Naocs作为注册中心的时候我们使用 RestTemplate+Ribbo 的方式访问到了procider发布的服务, 但是在实际开发中不可能使用这种方式进行服务调用,所以这章我们讲一下:使用 Naocs集成OpenFegin 来完成调用服务发布的接口。
OpenFegin 自身整合了Ribbon合Hystrix, 为服务调用提供了更优雅的方式
Ribbon:负载均衡
Hystrix: 断路器,Hystrix能够保证在一个依赖出现问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
上一章 创建了 服务发布者 provider 服务消费者 consumer
这一章 我们重新创建一个新的 集成openFegin的消费者
- open-fegin
demo项目git地址: https://gitee.com/DianHaiShiYuDeMing/nacos-demo
创建项目 pom.xmlappliaction.propertiescom.example nacos-demo 1.0.0 4.0.0 open-fegin com.example.consumer 0.0.1-SNAPSHOT open-fegin Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery org.springframework.cloud spring-cloud-starter-openfeign 2.2.5.RELEASE org.springframework.boot spring-boot-maven-plugin
server.port=8030 ###nacos spring.application.name=open-fegin spring.cloud.nacos.discovery.namespace=evone spring.cloud.nacos.username=evone spring.cloud.nacos.password=evone123456 spring.cloud.nacos.server-addr=127.0.0.1:16848启动类
package com.example.fegin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient// 开启nacos 服务发现
@EnableFeignClients(basePackages = "com.example.fegin")
public class OpenFeginApplication {
public static void main(String[] args) {
SpringApplication.run(OpenFeginApplication.class, args);
}
}
Cotrolller 接口类
package com.example.fegin.controller;
import com.example.fegin.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FeginContoller {
@Autowired
private DemoService demoService;
@GetMapping("/test/{id}")
public Object test(@PathVariable String id) {
String forObject = demoService.test(id);
return forObject;
}
}
启动测试
总结& 使用注意事项
Spring Cloud Openfegin 自动集成了 Ribbon 与 Hystrix;
在pom坐标使用过程中 OpenFegin 要使用与 nacos-discovery 的版本不一样的话 可能造成依赖jar包坐标版本冲突,导致依赖jar 下不下来 出现各种各样的问题 例如
java.lang.ClassNotFoundException: com.netflix.config.CachedDynamicIntProperty
需要单独引入引入
com.netflix.archaius archaius-core 0.7.6 com.google.guava guava



