springboot2.1.*集成nacos和feign進行服務注冊發現和調用,我要加入nacos的應用是一個單體多模塊的springboot 2.1.8版本的Java應用。
1,引入和版本
版本這里springboot與springcloud的版本不對應會導致報錯。nacos.version也可以用2.1.2.RELEASE
pom文件:
<nacos.version>2.1.1.RELEASE</nacos.version> <spring-cloud.version>Greenwich.SR4</spring-cloud.version>
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>${nacos.version}</version> </dependency> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
以及
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2,@EnableFeignClients
可以啟動類直接添加。
@SpringBootApplication @EnableFeignClients // add public class AppRun { public static void main(String[] args) { SpringApplication.run(AppRun.class, args); } }
3,配置
這里是一個基於本地的配置文件風格,如果不想改變風格,不使用nacos的配置功能,可以直接在對應配置文件中添加。
主配置:
spring.application.name=appname management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always spring.cloud.nacos.discovery.enabled=true spring.cloud.nacos.discovery.service=${spring.application.name} spring.cloud.nacos.discovery.group=yourgroupname
環境配置:
spring.cloud.nacos.discovery.namespace=dev spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
4,客戶端編寫
調用其他服務前,當然先看下別的服務的請求和返回,這里以一個全局唯一ID服務為例,入參一個業務類型,返回一個通用體包裝下的long型id為例。
請求:
curl -X POST "http://192.168.168.85:8100/cbid/get/id/v1" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"bizTag\": \"user_id\"}"
返回:
{ "body": { "id": 2015 }, "errorDesc": null, "retCode": "0000", "retMsg": null, "success": true }
基於這個接口,編寫客戶端:
@FeignClient(value = "id-genetator", path = "/id/get", contextId = "test") public interface IdGeneratorClient { @PostMapping(value = "/v1", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody RemoteBaseRsp<IdGeneratorRsp> getId(@RequestBody IdGeneratorReq bizTag); }
public class RemoteBaseRsp<T> { private T body; private String errorDesc; private String retCode; private String retMsg; private Boolean success; }
IdGeneratorRsp和IdGeneratorReq就是兩個對象。里面是具體的參數請求和返回。
5,調用測試
注入客戶端,調用。
@Autowired private IdGeneratorClient idGeneratorClient; @Test public String get(){ RemoteBaseRsp<IdGeneratorRsp> test = idGeneratorClient.getId(IdGeneratorReq.builder().bizTag("test").build()); if(!test.getSuccess() || null == test.getBody()){ // 基礎服務不可用,需要報系統異常 log.error("idGeneratorClient.getId 獲取異常,請檢查cbid"); // do error } // do sth. log.info("aa="+test); log.info("bb="+test.getBody().getId()); }