[英]How to manually inject Eureka Server?
我嘗試在一個Spring Boot工程中手動注入Eureka Server來模擬@EnableEurekaServer的效果。 我試過了:
@Bean
@ConditionalOnProperty(
value = "sd.mode",
havingValue = "Server")
public EurekaServerAutoConfiguration startServer() {
return new EurekaServerAutoConfiguration();
}
和
@EnableEurekaServer
@Configuration
@ConditionalOnProperty(
value = "sd.mode",
havingValue = "Server")
public class SDServer {
}
沒有一個按預期工作。 有沒有正確的方法來做到這一點?
編輯:澄清這個目標:
我想增強具有服務發現功能的 Spring Boot 應用程序。 第一步是根據其角色使 jar 可配置。 這適用於很多組件,只是 Eureka 給我帶來了麻煩。 目標是:
(在 application.properties 中)
sd.mode=server //Application loads Eureka Server
sd.mode=client //Application runs as Eureka Client
sd.mode=off //Application does not use Eureka
作為工作組件的示例:
@Configuration
public class OutputConfiguration {
@Bean
@ConditionalOnProperty(
value = "output",
havingValue = "ConsoleLogger",
matchIfMissing = false)
public Output<String, String> createConsoleLogger() {
return new ConsoleLogger();
}
@Bean
@ConditionalOnProperty(
value = "output",
havingValue = "TCPSocketWriter",
matchIfMissing = false)
public Output<String, String> createTCPSocketWriter() {
return new TCPSocketWriter();
}
}
這樣,我就可以訪問Output
並使用我在應用程序屬性中聲明的實例。 我想對尤里卡做類似的事情。
Edit2:我對 M. Deinums 解決方案的嘗試(如果我理解正確的話)沒有顯示出任何差異。
public class SDServer {
@Bean
public SDServerConfig createSDServerConfig(){
return new SDServerConfig();
}
@Configuration
@EnableEurekaServer
class SDServerConfig{
}
}
由......運營
@Configuration
public class ServiceDiscovery {
@Bean
@ConditionalOnProperty(
value = "sd.mode",
havingValue = "Server",
matchIfMissing = false)
public SDServer startServer() {
return new SDServer();
}
@Bean
@ConditionalOnProperty(
value = "sd.mode",
havingValue = "Client",
matchIfMissing = false)
public SDClient enableClient() {
return new SDClient();
}
}
順便說一句,SDClient 與
@EnableDiscoveryClient
public class SDClient {
}
按預期工作。
正確應用 M. Deinums 解決方案后,這終於奏效了!
@Configuration
@ConditionalOnProperty(
value = "sd.mode",
havingValue = "Server",
matchIfMissing = false)
public class SDServer {
@Configuration
@EnableEurekaServer
static class SDServerConfig {
}
}
您真的需要配置或 bean 注釋嗎? 一般的做法是像下面的代碼在main class中做
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
我不確定你想要達到什么目的。
我想你可以使用尤里卡服務器和客戶端。 在eureka server項目中添加spring-cloud-starter.netflix-eureka-client
依賴,在main class中使用如下注解。
eureka:
client:
registerWithEureka: false
fetchRegistry: false
server:
waitTimeInMsWhenSyncEmpty: 0
instance:
hostname: localhost
yml文件服務器中:端口:8761
eureka:
client:
registerWithEureka: false
fetchRegistry: false
server:
waitTimeInMsWhenSyncEmpty: 0
instance:
hostname: localhost
而對於你想在服務器中注冊的其他服務,你也必須使用相同的依賴。 但是,您必須在配置文件中使用以下行
spring.application.name=app-name
eureka.instance.hostname=localhost
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.