spring - 未连接时的Spring Eureka LoadBalanced RestTemplate
问题描述
这是我的依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
当我的 Spring Boot 应用程序在 Eureka 中注册时,我可以RestTemplate
像这样定义一个 bean:
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
在我的服务中,我可以使用它们的注册向其他服务发出请求spring.application.name
:
restTemplate.getForEntity("http://application1/test", String.class);
如何定义http://application1/
禁用 Eureka 的位置?
eureka.client.enabled=false
当前实施测试:
@Configuration
public class RibbonConfig {
@Bean
public ServerList<Server> serverServerList() {
return new ConfigurationBasedServerList();
}
}
@Configuration
public class WebConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Component
public class TestService implements CommandLineRunner {
@Autowired
private RestTemplate restTemplate;
@Override
public void run(String... args) throws Exception {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://application1/test", String.class);
System.out.println(responseEntity);
}
}
@RibbonClient(value = "application1", configuration = RibbonConfig.class)
@SpringBootApplication
public class Demo5Application {
public static void main(String[] args) {
SpringApplication.run(Demo5Application.class, args);
}
}
引导程序.yml
eureka:
client:
enabled: false
application1:
ribbon:
list-of-servers: http://localhost:8081/
解决方案
您可以通过这种方式为您的服务定义一个新的 RibbonClient 配置:
@Configuration
@RibbonClient(name = "application1", configuration = Application1RibbonClientConfiguration.class)
public class Application {
...
}
class Application1RibbonClientConfiguration{
@Bean
public ServerList<Server> ribbonServerList() {
return new ConfigurationBasedServerList();
}
}
如果您在 classPath 上没有 eureka,则可以跳过上面的所有配置
接下来在您的属性文件中,您可以列出所有服务器的位置,如下所示:
application1.ribbon.listOfServers=..,..,..
推荐阅读
- c# - 如何在运行时更改 url 徽标
- regex - 正则表达式无法对两个匹配项使用相同的字符
- html - CSS 元素出现在当前行下方。怎么修?
- xcode - 如何消除有关 MobileCoreServices 和 AssetsLibrary 的 Xcode 11.4 警告?
- php - 双击单个链接
- python - 如何将 python 模块 timeago 与烧瓶一起使用?
- javascript - 我如何根据两个选择选项打开弹出窗口
- jquery - 使用jsp更新MySQL表中的记录失败
- php - 使用laravel将普通密码IN数据库转换为加密密码?
- javascript - 用于登录的弹出窗口