获取服务地址

  使用的EurekaClient : getNextServerFromEureka()

   使用的DiscoveryClient: getInstances()

Load Balancer Client  (负载均衡客户端)

  加上@LoadBalaced: 为RestTemplate 或WebClient增加负载均衡的支持。

  Load Balancer Client 的简单使用

  pom文件的引入

/**指定spring-cloud.version**/
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
/**在注册的时候提供信息*/
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> /**dependencyManagement 引入springCloud Dependency*/
<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>

bootstarp.properties文件的简单配置

#声明服务名称
spring.application.name=my-customer-service

application.properties声明端口号

#随机端口
server.port=0

显示声明开启DiscoveryClient

在Application启动类上添加 ,@EnableDiscoveryClient注解

定义requestFactory

   @Bean
public HttpComponentsClientHttpRequestFactory requestFactory() {
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
connectionManager.setMaxTotal(200);
connectionManager.setDefaultMaxPerRoute(20); CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.evictIdleConnections(30, TimeUnit.SECONDS)
.disableAutomaticRetries()
// 有 Keep-Alive 认里面的值,没有的话永久有效
//.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
// 换成自定义的
.setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy())
.build(); HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpClient); return requestFactory;
}
CustomConnectionKeepAliveStrategy
public class CustomConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
private final long DEFAULT_SECONDS = 30; @Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
return Arrays.asList(response.getHeaders(HTTP.CONN_KEEP_ALIVE))
.stream()
.filter(h -> StringUtils.equalsIgnoreCase(h.getName(), "timeout")
&& StringUtils.isNumeric(h.getValue()))
.findFirst()
.map(h -> NumberUtils.toLong(h.getValue(), DEFAULT_SECONDS))
.orElse(DEFAULT_SECONDS) * 1000;
}
}

注入RestTemplate

  @LoadBalanced
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofMillis(100))
.setReadTimeout(Duration.ofMillis(500))
.requestFactory(this::requestFactory)
.build();
}

RestTemplate的使用


@Autowired
private RestTemplate restTemplate; // 请求列表数据
ResponseEntity<List<Info>> list = restTemplate
.exchange("请求的服务地址", HttpMethod.GET, null, ptr);
list.getBody().forEach(c -> log.info("info": {}", c)); // 插入数据
MyRequest orderRequest = MyRequest.builder()
.param("value1")
// 集合数据
.param(Arrays.asList("value2"))
.build(); RequestEntity<MyRequest> request = RequestEntity
.post(UriComponentsBuilder.fromUriString("服务地址").build().toUri())
.body(orderRequest); ResponseEntity<Order> response = restTemplate.exchange(request, Order.class);

Order order = restTemplate
.getForObject("http://waiter-service/order/{id}", Order.class, id);

  


Spring Cloud 使用Spring Cloud Loadbalancer访问服务地址的更多相关文章

  1. 使用Spring Session实现Spring Boot水平扩展

    小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...

  2. 【spring boot】spring cloud下spring boot微服务启动没有报错,但是访问访问不到

    spring cloud下spring boot微服务启动没有报错,但是访问访问不到 解决方法: 可能是端口被占用了,但是依旧启用成功了. 更改一下项目启用的端口号,再重新启动查看是否可以正常访问.

  3. 基于Spring Cloud和Netflix OSS 构建微服务-Part 1

    前一篇文章<微服务操作模型>中,我们定义了微服务使用的操作模型.这篇文章中,我们将开始使用Spring Cloud和Netflix OSS实现这一模型,包含核心部分:服务发现(Servic ...

  4. Spring Cloud(二)服务提供者 Eureka + 服务消费者(rest + Ribbon)

    Ribbon是什么? Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起.Ribbon客户端组件提供一系列完善的配置项如连接超时 ...

  5. 基于Spring Cloud和Netflix OSS构建微服务,Part 2

    在上一篇文章中,我们已使用Spring Cloud和Netflix OSS中的核心组件,如Eureka.Ribbon和Zuul,部分实现了操作模型(operations model),允许单独部署的微 ...

  6. Spring Cloud 入门教程 - 搭建配置中心服务

    简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...

  7. 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践

    由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...

  8. maven 聚合工程 用spring boot 搭建 spring cloud 微服务 模块式开发项目

    项目的简单介绍: 项目采用maven聚合工程 用spring boot 搭建 spring cloud的微服务 模块式开发 项目的截图: 搭建开始: 能上图 我少打字 1.首先搭建maven的聚合工程 ...

  9. Spring Cloud(Dalston.SR5)--Zuul 网关-微服务集群

    通过 url 映射的方式来实现 zuul 的转发有局限性,比如每增加一个服务就需要配置一条内容,另外后端的服务如果是动态来提供,就不能采用这种方案来配置了.实际上在实现微服务架构时,服务名与服务实例地 ...

随机推荐

  1. 让 Git Bisect 帮助你

    让 Git Bisect 帮助你 英文原文:Letting Git Bisect Help You   Git 提供来很多的工具来帮助我们改进工作流程. bisect 命令就是其中之一, 虽然由于使用 ...

  2. JavaScript深入之变量对象(转载)

    前言 在上篇<JavaScript深入之执行上下文栈>中讲到,当 JavaScript 代码执行一段可执行代码(executable code)时,会创建对应的执行上下文(executio ...

  3. 关于微信小程序的一些总结

    mpvue? {{}} 在vue和小程序中的区别? 01 小程序中{{}}和vue中的{{}}用法基本一致,可以显示data中的数据,可以写表达式 不一样的地方? 01 小程序的{{}}可以写在属性中 ...

  4. 解决:Module not found: node_modules\sass-loader\package.json (directory description file)

    npm uninstall node-sass npm install node-sass@latest

  5. Cheatsheet: 2019 07.01 ~ 09.30

    Other Intro Guide to Dockerfile Best Practices QuickJS Javascript Engine Questions for a new technol ...

  6. php之ob_start()缓冲区

    ob_get_contents()函数及与其相关几个函数的用法 ob_start() ob_get_contents(); 获取缓冲区内容,如果是纯 html内容或标签,则都会放于浏览器的缓冲区中. ...

  7. Python Web开发:Django+BootStrap实现简单的博客项目

    创建blog的项目结构 关于如何创建一个Django项目,请查看[Python Web开发:使用Django框架创建HolleWorld项目] 创建blog的数据模型 创建一个文章类 所有开发都是数据 ...

  8. 2019-1-25-WPF-ListBox-的选择

    title author date CreateTime categories WPF ListBox 的选择 lindexi 2019-01-25 21:43:17 +0800 2018-2-13 ...

  9. ssh 操作 esxi 基本命令

    1.查看虚拟机: vim-cmd vmsvc/getallvms 会显示当前esxi上的虚拟机数量,没一个都有编号. 2.停用虚拟机:vim-cmd vmsvc/power.suspend + 之前命 ...

  10. Java疯狂讲义笔记——内部类

    [定义]内部类:定义在其它类内部的类.外部类:包含内部类的类,也称 宿主类.局部内部类:定义在方法里的内部类. [接口内部类]接口中也可以定义内部类,必须为public static修饰(自动添加), ...