Spring cloud配置Ribbon用于负载君和,如果要在细节上配置更多,那么需要阅读一下官方文档。
* RoundRobinRule:轮询 * RandomRule:随机 * AvailabilityFilteringRule: 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,以及并发的连接数量 * 超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问; * WeightedResponseTimeRule: 根据平均响应时间计算所有服务的权重,响应时间越快,服务权重越大,被选中的机率越高; * 刚启动时,如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够时,会切换到WeightedResponseTimeRule * RetryRule: 先按照RoundRobinRule的策略获取服务,如果获取服务失败,则在指定时间内会进行重试,获取可用的服务; * BestAvailableRule: 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务; * ZoneAvoidanceRule: 默认规则,复合判断server所在区域的性能和server的可用性选择服务器;
首先maven文件:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.test</groupId> <artifactId>router</artifactId> <version>0.0.1-SNAPSHOT</version> <name>router</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.M3</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <dependencyManagement> <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> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> </project>
配置文件:
server: address: 127.0.0.1 port: 7001 undertow: io-threads: 19 # 设置IO线程数, 它主要执行非阻塞的任务,它们会负责多个连接, 默认设置每个CPU核心一个线程 worker-threads: 24 # 阻塞任务线程池, 当执行类似servlet请求阻塞操作, undertow会从这个线程池中取得线程,它的值设置取决于系统的负载 buffer-size: 1024 # 以下的配置会影响buffer,这些buffer会用于服务器连接的IO操作,有点类似netty的池化内存管理 direct-buffers: true # 是否分配的直接内存 always-set-keep-alive: true #socket-binding="http",保持长连接 spring: application: name: router-server profiles: active: test cloud: loadbalancer: retry: enabled: true #重试机制开启为true,关闭为false eureka: instance: appname: router-server virtual-host-name: router-server secure-virtual-host-name: router-server instance-id: ${server.address}:router-server-peer:${server.port} hostname: localhost # non-secure-port: 6001 #非安全通信端口 # non-secure-port-enabled: true #是否启用非安全端口接受请求 # secure-port: 6444 #安全通信端口 # secure-port-enabled: true #是否启用安全端口接受请求 prefer-ip-address: false #是否优先使用IP地址作为主机名的标识,默认false lease-renewal-interval-in-seconds: 30 #eureka节点定时续约时间,默认30 lease-expiration-duration-in-seconds: 90 #eureka节点剔除时间,默认90 client: register-with-eureka: true #将自己注册到eureka注册中心,单节点关闭 fetch-registry: true #从注册中心获取注册信息,单节点关闭 registry-fetch-interval-seconds: 30 #从注册中心获取注册信息的时间间隔 eureka-server-connect-timeout-seconds: 15 eureka-server-read-timeout-seconds: 10 service-url: defaultZone: http://${eureka.instance.hostname}:7000/eureka/ #注册到另外两个节点,实现集群 ribbon: eureka: enabled: true
注解开启服务:
@EnableEurekaClient @SpringBootApplication public class RouterApplication { public static void main(String[] args) { SpringApplication.run(RouterApplication.class, args); } }
写一个RestTemplate服务层,用于公共接口转发:
package com.test.router.system.service; import com.test.router.system.core.BaseService; import com.test.router.system.core.ResultResp; import com.test.router.system.service.resources.IAPIDispatcherService; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.util.Map; @Service public class APIDispatcherServiceImpl extends BaseService implements IAPIDispatcherService { @Resource private RestTemplate restTemplate; @Override public ResultResp<Map<String, Object>> getForObject(String name, Object... uriVariables) { return restTemplate.getForObject("http://api-server/" + name, ResultResp.class); } @Override public ResultResp<Map<String, Object>> postForObject(String name, Map<String, Object> body) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map<String, Object>> data = new HttpEntity<>(body,headers); ResponseEntity<ResultResp> resp = restTemplate.postForEntity("http://api-server/" + name , data, ResultResp.class); return resp.getBody(); } @Override public ResultResp<Map<String, Object>> putForObject(String name, Integer id, Map<String, Object> body) { HttpEntity<Map<String, Object>> data = new HttpEntity<>(body); ResponseEntity<ResultResp> resp = restTemplate.exchange("http://api-server/" + name + "/{1}", HttpMethod.PUT, data, ResultResp.class, id); return resp.getBody(); } @Override public ResultResp<Map<String, Object>> deleteForObject(String name, Integer id) { ResponseEntity<ResultResp> resp = restTemplate.exchange("http://api-server/" + name + "/{1}", HttpMethod.PUT, null, ResultResp.class, id); return resp.getBody(); } }
最后需要一个控制器,用于转发使用:
package com.test.router.app.v1; import com.test.router.app.base.BaseV1Controller; import com.test.router.constant.Constant; import com.test.router.system.base.IDefaultRestController; import com.test.router.system.core.ResultResp; import com.test.router.system.model.http.Request; import com.test.router.system.service.resources.IAPIDispatcherService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; @RestController public class TestController extends BaseV1Controller implements IDefaultRestController { @Resource private IAPIDispatcherService dispatcherService; /** * http://127.0.0.1:7001/v1/router?name=v2/test&namespace=api&user=avc * @param request * @param response * @return */ @RequestMapping(value = "/router", method = RequestMethod.GET) @Override public ResultResp<Map<String, Object>> doGet(HttpServletRequest request, HttpServletResponse response) { String namespace = request.getParameter("namespace"); String name = request.getParameter("name"); if (Constant.NAMESPACE_API.equals(namespace)) { Map<String, String> args = this.initUriVariables(name, request); StringBuffer sb = new StringBuffer(); if (name.lastIndexOf("?") == -1) { name += "?"; } sb.append(name); args.forEach((k, v) -> { sb.append(k).append("=").append(v).append("&"); }); return dispatcherService.getForObject(sb.toString(), null); } return new ResultResp<>(); } /** * http://127.0.0.1:7001/v1/router?user=avc * * * { * "header":{ * "namespace":"api", * "name":"v2/test" * }, * "payload":{ * "username":"张三", * "age":15 * } * } * @param body * @param request * @param response * @return */ @RequestMapping(value = "/router", method = RequestMethod.POST) @Override public ResultResp<Map<String, Object>> doPost(@RequestBody Request<Map<String, Object>> body, HttpServletRequest request, HttpServletResponse response) { String namespace = body.getHeader().getNamespace(); String name = body.getHeader().getName(); if (Constant.NAMESPACE_API.equals(namespace)) { Map<String, String> args = this.initUriVariables(name, request); StringBuffer sb = new StringBuffer(); if (name.lastIndexOf("?") == -1) { name += "?"; } sb.append(name); args.forEach((k, v) -> { sb.append(k).append("=").append(v).append("&"); }); return dispatcherService.postForObject(sb.toString(), body.getPayload()); } return new ResultResp<>(); } @Override public ResultResp<Map<String, Object>> doPut(@PathVariable Integer id, @RequestBody Request<Map<String, Object>> obj, HttpServletRequest request, HttpServletResponse response) { return null; } @Override public ResultResp<Map<String, Object>> doDelete(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) { return null; } }
这样子基本上完成,主要使用浏览器打开http://127.0.0.1:7001/v1/router?name=v2/test&namespace=api&user=avc,就会根据name对应的值去获取api-service的对应的接口。
更多请参阅:
https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.2.0.RC1/reference/html/#spring-cloud-ribbon
近期评论