【问题标题】:Spring Eureka LoadBalanced RestTemplate when not connected未连接时的Spring Eureka LoadBalanced RestTemplate
【发布时间】:2020-04-30 04:04:08
【问题描述】:

这是我的依赖项:

<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);
  }
}

bootstrap.yml

eureka:
  client:
    enabled: false

application1:
  ribbon:
    list-of-servers: http://localhost:8081/

【问题讨论】:

  • 为什么不用 feign 客户端而不是 RestTemplate

标签: spring spring-boot load-balancing netflix-eureka


【解决方案1】:

您可以通过这种方式为您的服务定义新的 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=..,..,..

【讨论】:

  • 我得到了一个 NPE。看起来IClientConfig 还没有初始化?到目前为止,我已经添加了所有内容。
  • 您可以将异常堆栈添加到您的帖子中吗?
猜你喜欢
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2014-12-04
  • 2017-11-14
  • 1970-01-01
  • 2017-10-10
  • 2016-05-02
  • 2020-04-06
相关资源
最近更新 更多