SpringCloud服務(wù)實(shí)現(xiàn)同時(shí)使用eureka和nacos方法
一,背景
之所以會(huì)想到一個(gè)服務(wù)同時(shí)使用eureka和nacos,是因?yàn)橛龅揭粋€(gè)需求,配置數(shù)據(jù)是存儲(chǔ)在nacos的配置中,然后使用該配置的服務(wù)卻是在一個(gè)eureka環(huán)境中。所以此時(shí)就需要一個(gè)代理服務(wù),它既能夠從nacos的config中獲取配置數(shù)據(jù),又是注冊(cè)到eureka注冊(cè)中心中。
二,代理服務(wù)創(chuàng)建和配置
2.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>lmc-tools</artifactId> <groupId>com.lmc</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>tools-2-eureka-nacos</artifactId> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>com.lmc</groupId> <artifactId>tools-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- <dependency>--> <!-- <groupId>com.alibaba.cloud</groupId>--> <!-- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>--> <!-- <version>2021.1</version>--> <!-- </dependency>--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>2021.1</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> <version>3.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
注意,關(guān)于nacos,在該服務(wù)中不能引入spring-cloud-starter-alibaba-nacos-discovery依賴,只需要引入spring-cloud-starter-alibaba-nacos-config
2.2 bootstrap.yml
server:
port: 9006
servlet:
context-path: /eureka-proxyspring:
application:
name: tools-eureka-proxy
profiles:
active: dev
management:
endpoints:
web:
exposure:
include: "*"
bootstrap-dev.yml
spring:
cloud:
nacos:
server-addr: localhost:9000
config:
namespace: 8628e5dd-a236-4016-b94f-565a001faf2f
file-extension: yaml # 配置內(nèi)容的數(shù)據(jù)格式
extension-configs[0]:
data-id: ${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
group: dev
refresh: trueeureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
registry-fetch-interval-seconds: 10
instance:
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # 實(shí)例名:application:ip:port
prefer-ip-address: true # 優(yōu)先使用IP地址作為主機(jī)名的標(biāo)識(shí)
lease-renewal-interval-in-seconds: 180 # 續(xù)約更新時(shí)間間隔
lease-expiration-duration-in-seconds: 200
2.3 Application.java
package per.lmc.tools2.eureka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @Description: TODO * @version: 1.0 */ @SpringBootApplication @EnableDiscoveryClient public class EurekaProxyApplication { public static void main(String[] args) { SpringApplication.run(EurekaProxyApplication.class, args); } }
2.4 創(chuàng)建接口
2.4.1 ApiMessageController.java
package per.lmc.tools2.eureka.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import per.lmc.tools2.eureka.config.MyNacosProperties; import com.lmc.common.enums.LanguageEnum; import com.lmc.common.enums.SplitEnum; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @Description: TODO API返回參數(shù)接口 * @version: 1.0 */ @RestController @RequestMapping("/apiMessages") public class ApiMessageController { @Autowired private MyNacosProperties myNacosProperties; /** * 獲取所有apiMessages * @param language 語(yǔ)言 * @return 數(shù)據(jù)集合 */ @GetMapping("/getAll") public Map<String, String> apiMessages(String language) { List<String> apiMessages = myNacosProperties.getApiMessages(); Map<String, String> result = new HashMap<>(20); if (!CollectionUtils.isEmpty(apiMessages)) { if (LanguageEnum.English.value().equalsIgnoreCase(language)) { apiMessages.forEach(a -> result.put(a.split(SplitEnum.API_MESSAGE_SPLIT.value())[0], a.split(SplitEnum.API_MESSAGE_SPLIT.value())[2])); }else { apiMessages.forEach(a -> result.put(a.split(SplitEnum.API_MESSAGE_SPLIT.value())[0], a.split(SplitEnum.API_MESSAGE_SPLIT.value())[1])); } } return result; } /** * 通過(guò)code獲取APIMessage * @param language 語(yǔ)言 * @param code 參數(shù)代碼 * @return 參數(shù)代碼指定信息 */ @GetMapping("/getOne") public String getMessage(String language, String code) { // 獲取指定code的記錄 List<String> apiMessages = myNacosProperties.getApiMessages().stream().filter(a -> a.startsWith(code)).collect(Collectors.toList()); if (CollectionUtils.isEmpty(apiMessages)) { return String.format("不存在code為%s的記錄", code); } if (LanguageEnum.English.value().equalsIgnoreCase(language)) { return apiMessages.get(0).split(SplitEnum.API_MESSAGE_SPLIT.value())[2]; }else { return apiMessages.get(0).split(SplitEnum.API_MESSAGE_SPLIT.value())[1]; } } }
2.4.2 MyNacosProperties.java
package per.lmc.tools2.eureka.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Configuration; import java.util.List; /** * @Description: TODO Nacos配置映射類 * @version: 1.0 */ @Configuration @ConfigurationProperties(prefix = "tools") @RefreshScope @Data public class MyNacosProperties { List<String> apiMessages; }
在nacos中的配置如下所示:
2.5 運(yùn)行測(cè)試
運(yùn)行服務(wù),訪問(wèn) http://localhost:9006/eureka-proxy/apiMessages/getAll?language=en,能成功獲取到數(shù)據(jù)
{"1000":"missing parameter","2000":"server internal exception","0000":"operation succeeded"}
三,將該服務(wù)引入eureka注冊(cè)中心
上面服務(wù)實(shí)際上已經(jīng)注冊(cè)到eureka注冊(cè)中心中,但是,實(shí)際上使用中,我們都是通過(guò)網(wǎng)關(guān)訪問(wèn)的,所以在網(wǎng)關(guān)服務(wù)的application.yml中,補(bǔ)充下該服務(wù)的路由
server:
port: 8764
servlet:
context-path: /lmcspring:
application:
name: tools-gateway
profiles:
active: dev
cloud:
# 消息總線
bus:
trace:
enabled: true
# 網(wǎng)關(guān)配置
gateway:
discovery:
locator:
enabled: true # 開(kāi)啟根據(jù)注冊(cè)中心路由,并隨服務(wù)的改變而改變路由
lower-case-service-id: true # 開(kāi)啟服務(wù)名轉(zhuǎn)為小寫
# globalcors:
# default-filters:
# - PreserveHostHeader #發(fā)送原主機(jī)頭
routes:
- id: tools-task
uri: lb://tools-task
# uri: http://localhost:8083
predicates:
- Path=/tltk/**
- id: tools-admin
uri: lb://tools-admin
predicates:
- Path=/monitor/**
filters:
- PreserveHostHeader #發(fā)送網(wǎng)關(guān)原始主機(jī)頭
- id: tools-demo
uri: lb://tools-demo
predicates:
- Path=/demo/**
- id: tools-eureka-proxy
uri: lb://tools-eureka-proxy
predicates:
- Path=/eureka-proxy/**eureka:
client:
registry-fetch-interval-seconds: 10
instance:
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # 實(shí)例名:application:ip:port
prefer-ip-address: true # 優(yōu)先使用IP地址作為主機(jī)名的標(biāo)識(shí)
lease-renewal-interval-in-seconds: 180 # 續(xù)約更新時(shí)間間隔
lease-expiration-duration-in-seconds: 200
# 項(xiàng)目配置有 server.servlet.context-path 屬性,想要被 spring boot admin 監(jiān)控,就要配置以下屬性
health-check-url: http://${spring.cloud.client.ip-address}:${server.port}/actuator/health# 暴露監(jiān)控?cái)帱c(diǎn)
management:
endpoints:
web:
exposure:
include: "*"
health:
show-details: alwayslogging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n"
然后重啟網(wǎng)關(guān)服務(wù),訪問(wèn) http://localhost:8764/eureka-proxy/apiMessages/getAll,得到
{"1000":"缺少參數(shù)","2000":"服務(wù)器內(nèi)部異常","0000":"操作成功"}
因此,eureka成功從nacos獲取數(shù)據(jù)。
到此這篇關(guān)于SpringCloud服務(wù)實(shí)現(xiàn)同時(shí)使用eureka和nacos方法介紹的文章就介紹到這了,更多相關(guān)SpringCloud eureka和nacos內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot排除不需要的自動(dòng)配置類DataSourceAutoConfiguration問(wèn)題
這篇文章主要介紹了SpringBoot排除不需要的自動(dòng)配置類DataSourceAutoConfiguration問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07SpringBoot常用數(shù)據(jù)庫(kù)開(kāi)發(fā)技術(shù)匯總介紹
Spring Boot常用的數(shù)據(jù)庫(kù)開(kāi)發(fā)技術(shù)有JDBCTemplate、JPA和Mybatis,它們分別具有不同的特點(diǎn)和適用場(chǎng)景,可以根據(jù)具體的需求選擇合適的技術(shù)來(lái)進(jìn)行開(kāi)發(fā)2023-04-04Mybatis中SqlSession接口中selectList方法詳解
這篇文章主要給大家介紹了關(guān)于Mybatis中SqlSession接口中selectList方法的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-03-03Spring中的AOP動(dòng)態(tài)代理源碼詳解
這篇文章主要介紹了Spring中的AOP動(dòng)態(tài)代理源碼詳解,AOP即面向切面編程也稱面向方面編程,它是面向?qū)ο缶幊蘋OP的一種補(bǔ)充,目前已成為一種比較成熟的編程方式,本文就其源碼進(jìn)行解析,需要的朋友可以參考下2023-09-09解決Mybatis 大數(shù)據(jù)量的批量insert問(wèn)題
這篇文章主要介紹了解決Mybatis 大數(shù)據(jù)量的批量insert問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01Java使用Arrays.asList報(bào)UnsupportedOperationException的解決
這篇文章主要介紹了Java使用Arrays.asList報(bào)UnsupportedOperationException的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04