SpringCloud:如何使用SpringCloud搭建一个简单的微服务

缺乏、安全感 2022-02-23 00:48 344阅读 0赞

在构建微服务时,最常用的就是SpringCloud,其中的Netflix-Eureka用的最多,本文主要讲讲如何使用它。

一、配置注册服务器(Registry Server/Eureka Server)

Maven配置:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>TestCloud</groupId>
  6. <artifactId>TestCloud-ServiceRegistry</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>TestCloud-ServiceRegistry</name>
  10. <url>http://maven.apache.org</url>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>1.8</maven.compiler.source>
  14. <maven.compiler.target>1.8</maven.compiler.target>
  15. <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
  16. </properties>
  17. <parent>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-parent</artifactId>
  20. <version>2.1.3.RELEASE</version>
  21. <relativePath />
  22. </parent>
  23. <dependencyManagement>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.springframework.cloud</groupId>
  27. <artifactId>spring-cloud-dependencies</artifactId>
  28. <version>Greenwich.SR1</version>
  29. <type>pom</type>
  30. <scope>import</scope>
  31. </dependency>
  32. </dependencies>
  33. </dependencyManagement>
  34. <dependencies>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-web</artifactId>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework.cloud</groupId>
  41. <artifactId>spring-cloud-starter</artifactId>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.cloud</groupId>
  45. <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  46. </dependency>
  47. <dependency>
  48. <groupId>junit</groupId>
  49. <artifactId>junit</artifactId>
  50. <scope>test</scope>
  51. </dependency>
  52. </dependencies>
  53. </project>

application.properties配置:

server.port=8761

eureka.instance.hostname=localhost
# eureka.datacenter=Main
# eureka.environment=prod

eureka.server.enableSelfPreservation=false

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

eureka.server.enableSelfPreservation - 当service server心跳超时后,是否还要将service server保存在列表中一段时间。 当网络发生短暂分区时,不会因为大量service server心跳超时,而将service server从列表中删除,从而造成客户端调用大面积失败的情况。
eureka.client.register-with-eureka - 是否将自身也作为service server注册到Eureka Server。
eureka.client.fetch-registry - 是否将自身作为service client从Eureka Server中获取service server列表。

ServiceRegistry代码:

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
  4. @SpringBootApplication
  5. @EnableEurekaServer
  6. public class ServiceRegistryEurekaApp {
  7. public static void main(String[] args) throws Exception {
  8. SpringApplication.run(ServiceRegistryEurekaApp.class, args);
  9. }
  10. }

程序运行后,可以通过访问如下地址访问Eureka Server管理控制台:
http://localhost:8761
当有service server注册上来后,可以通过如下地址查看注册的service server的信息:
http://localhost:8761/eureka/apps

二、配置服务服务器(Service Server/Eureka Client)

Maven配置:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>TestCloud</groupId>
  6. <artifactId>TestCloud-ServiceServer1</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>TestCloud-ServiceServer1</name>
  10. <url>http://maven.apache.org</url>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. </properties>
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>2.1.3.RELEASE</version>
  18. <relativePath />
  19. </parent>
  20. <dependencyManagement>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.cloud</groupId>
  24. <artifactId>spring-cloud-dependencies</artifactId>
  25. <version>Greenwich.SR1</version>
  26. <type>pom</type>
  27. <scope>import</scope>
  28. </dependency>
  29. </dependencies>
  30. </dependencyManagement>
  31. <dependencies>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-webflux</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-actuator</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework.cloud</groupId>
  42. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>junit</groupId>
  46. <artifactId>junit</artifactId>
  47. <scope>test</scope>
  48. </dependency>
  49. </dependencies>
  50. <build>
  51. <plugins>
  52. <plugin>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-maven-plugin</artifactId>
  55. </plugin>
  56. </plugins>
  57. </build>
  58. </project>

bootstrap.properties配置:

spring.profiles.active=test

spring.application.name=TestServer

# spring.main.allow-bean-definition-overriding=true
# spring.cloud.config.uri=http://localhost:8888

spring.cloud.discovery.enabled=true
spring.cloud.service-registry.auto-registration.enabled=true

spring.cloud.config.uri - 表示以后需要访问的配置服务器的地址。
spring.application.name - 表示此service注册到Registry上的服务名称。
spring.cloud.discovery.enabled - 表示是否打开发现服务,默认值为true。
spring.cloud.service-registry.auto-registration.enabled - 表示是否启动后自动注册,默认值为true。

注册可以使用Netflix-Eureka,也可以使用Zookeeper,以下使用Netflix-Eureka为例进行讲解。

application.properties配置:

server.port=8081

# http://localhost:8081/actuator/refresh
management.endpoints.web.exposure.include=refresh
# management.endpoints.jmx.exposure.exclude=*
# management.context-path=/base

eureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true

# eureka.client.healthcheck.enabled=true
# eureka.instance.statusPageUrlPath=${management.context-path}/info
# eureka.instance.healthCheckUrlPath=${management.context-path}/health

# eureka.instance.instanceId=${spring.application.name}:${random.int}

# hostname为此实例提供给外部调用的域名
eureka.instance.hostname=localhost
eureka.instance.leaseRenewalIntervalInSeconds=10
eureka.instance.leaseExpirationDurationInSeconds=20

eureka.instance.metadataMap.versions=v1

management.endpoints.web.exposure.include - 表示可以放开给外部访问的方法,访问方式:http://localhost:8081/actuator/XXX,其中XXX表示实际调用的方法。比如:management.endpoints.web.exposure.include=refresh表示允许通过访问http://localhost:8081/actuator/refresh,访问结果为重新加载@RefreshScope范围内的配置信息。

eureka.client.enabled - 表示是否启用eureka client
eureka.client.serviceUrl.defaultZone - 表示eureka client可以访问的eureka server的地址

eureka.instance.hostname - 为此实例提供给外部调用的域名。
eureka.instance.leaseRenewalIntervalInSeconds - 心跳间隔。如果连续3次心跳都无回复,表示心跳超时。
eureka.instance.leaseExpirationDurationInSeconds - 心跳超时后,此服务会在eureka server的列表中保持多长时间。

eureka.instance.metadataMap.versions - eureka.instance.metadataMap中可以添加用户自定义的任意属性。

此处分为application.properties和bootstrap.properties两个配置文件,主要是为以后连接Config Server做准备,因为service server启动后必须先访问Config Server获取配置信息,然后才能初始化service server。

Java代码:

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration;
  4. import org.springframework.context.ConfigurableApplicationContext;
  5. @SpringBootApplication(exclude = { TaskSchedulingAutoConfiguration.class })
  6. public class AppBoot {
  7. public static void main(String[] args) {
  8. ConfigurableApplicationContext ctx = SpringApplication.run(AppBoot.class, args);
  9. ctx.registerShutdownHook();
  10. }
  11. }

AppBoot负责启动整个应用

  1. import java.util.concurrent.Executor;
  2. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  3. import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.scheduling.annotation.EnableAsync;
  7. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  8. @Configuration
  9. @EnableDiscoveryClient
  10. @EnableAsync
  11. public class AppConf {
  12. private ServiceRegistry registry;
  13. public AppConf(ServiceRegistry registry) {
  14. this.registry = registry;
  15. }
  16. public ServiceRegistry getRegistry() {
  17. return registry;
  18. }
  19. @Bean(name = "taskExecutor")
  20. public Executor taskExecutor() {
  21. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  22. executor.setCorePoolSize(10);
  23. executor.setMaxPoolSize(20);
  24. executor.setQueueCapacity(200);
  25. executor.setKeepAliveSeconds(60);
  26. executor.setThreadNamePrefix("taskExec-");
  27. // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  28. return executor;
  29. }
  30. }

AppConf中获取ServiceRegistry,并生成一个线程池供以后使用。

  1. import java.util.List;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.cloud.client.ServiceInstance;
  4. import org.springframework.cloud.client.discovery.DiscoveryClient;
  5. import org.springframework.cloud.client.serviceregistry.Registration;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. @RequestMapping("/appCtrl")
  11. public class AppController {
  12. @Autowired
  13. private Registration registration;
  14. @Autowired
  15. private DiscoveryClient discoveryClient;
  16. @Autowired
  17. private AppConf configuration;
  18. @RequestMapping("/register")
  19. public void register() {
  20. configuration.getRegistry().register(registration);
  21. System.out.println("Host:" + registration.getHost());
  22. System.out.println("Port:" + registration.getPort());
  23. System.out.println("InstanceId:" + registration.getInstanceId());
  24. System.out.println("ServiceId:" + registration.getServiceId());
  25. System.out.println("Uri:" + registration.getUri());
  26. }
  27. @RequestMapping("/deregister")
  28. public void deregister() {
  29. configuration.getRegistry().deregister(registration);
  30. }
  31. @RequestMapping("/service-instances/{applicationName}")
  32. public List<ServiceInstance> serviceInstancesByApplicationName(@PathVariable String applicationName) {
  33. return this.discoveryClient.getInstances(applicationName);
  34. }
  35. }

registration本身也是一个service instance,它保存了当前Service Server的相关信息。discoveryClient可以获取Eureka Server上已注册的service instance。AppController可以注册此服务到Eureka Server,或从Eureka Server撤销此服务,也可以获取注册的服务信息。

应用启动后,就可以从Eureka Server的控制台上看到TestServer注册成功了。

关于service server自身的一些信息,可以直接访问http://localhost:8081/actuator中的一些命令获取。

如果不知道/actuator下面有哪些命令,可以通过访问http://localhost:8081/actuator获取所有可用的命令,返回结果为:

{“_links”:{
“self”:{“href”:”http://localhost:8081/actuator","templated":false
“archaius”:{“href”:”http://localhost:8081/actuator/archaius","templated":false
“auditevents”:{“href”:”http://localhost:8081/actuator/auditevents","templated":false
“beans”:{“href”:”http://localhost:8081/actuator/beans","templated":false
“caches-cache”:{“href”:”http://localhost:8081/actuator/caches/\{cache\}","templated":true
“caches”:{“href”:”http://localhost:8081/actuator/caches","templated":false
“health”:{“href”:”http://localhost:8081/actuator/health","templated":false
“health-component-instance”:{“href”:”http://localhost:8081/actuator/health/\{component\}/\{instance\}","templated":true
“health-component”:{“href”:”http://localhost:8081/actuator/health/\{component\}","templated":true
“conditions”:{“href”:”http://localhost:8081/actuator/conditions","templated":false
“configprops”:{“href”:”http://localhost:8081/actuator/configprops","templated":false
“env”:{“href”:”http://localhost:8081/actuator/env","templated":false
“env-toMatch”:{“href”:”http://localhost:8081/actuator/env/\{toMatch\}","templated":true
“info”:{“href”:”http://localhost:8081/actuator/info","templated":false
“loggers”:{“href”:”http://localhost:8081/actuator/loggers","templated":false
“loggers-name”:{“href”:”http://localhost:8081/actuator/loggers/\{name\}","templated":true
“heapdump”:{“href”:”http://localhost:8081/actuator/heapdump","templated":false
“threaddump”:{“href”:”http://localhost:8081/actuator/threaddump","templated":false
“metrics”:{“href”:”http://localhost:8081/actuator/metrics","templated":false
“metrics-requiredMetricName”:{“href”:”http://localhost:8081/actuator/metrics/\{requiredMetricName\}","templated":true
“scheduledtasks”:{“href”:”http://localhost:8081/actuator/scheduledtasks","templated":false
“httptrace”:{“href”:”http://localhost:8081/actuator/httptrace","templated":false
“mappings”:{“href”:”http://localhost:8081/actuator/mappings","templated":false
“refresh”:{“href”:”http://localhost:8081/actuator/refresh","templated":false
“features”:{“href”:”http://localhost:8081/actuator/features","templated":false
“service-registry”:{“href”:”http://localhost:8081/actuator/service-registry","templated":false\}
}}

再写一些业务代码,用于提供其它方法供调用:

  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.cloud.context.config.annotation.RefreshScope;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import com.jjhgame.test.service.TestService;
  9. @RefreshScope
  10. @RestController
  11. @RequestMapping("/base")
  12. public class MessageRestController {
  13. private static Logger log = LoggerFactory.getLogger(MessageRestController.class);
  14. @Autowired
  15. private TestService testService;
  16. @Value("${message:Hello default}")
  17. private String message;
  18. @RequestMapping("/message")
  19. String getMessage() {
  20. String ret = this.message + ":" + System.currentTimeMillis();
  21. String result = testService.getResult();
  22. return result;
  23. }
  24. }
  25. import org.slf4j.Logger;
  26. import org.slf4j.LoggerFactory;
  27. import org.springframework.scheduling.annotation.Async;
  28. import org.springframework.stereotype.Service;
  29. import com.jjhgame.test.web.MessageRestController;
  30. @Service
  31. public class TestService {
  32. private static Logger log = LoggerFactory.getLogger(MessageRestController.class);
  33. @Async("taskExecutor")
  34. public String getResult() {
  35. String name = "" + Thread.currentThread().getName();
  36. log.info("==============" + name);
  37. return name;
  38. }
  39. }

每次调用由@RefreshScope注释的Bean时,Bean都会重新生成。如果启动时连接了Config Server,@RefreshScope范围中的message会在调用http://localhost:8081/actuator/refresh后,重新从Config Server中获取新的值。

三、测试客户端

Maven配置:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>TestCloud</groupId>
  6. <artifactId>TestCloud-Client</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>TestCloud-Client</name>
  10. <url>http://maven.apache.org</url>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. </properties>
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>2.1.3.RELEASE</version>
  18. <relativePath />
  19. </parent>
  20. <dependencyManagement>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.cloud</groupId>
  24. <artifactId>spring-cloud-dependencies</artifactId>
  25. <version>Greenwich.SR1</version>
  26. <type>pom</type>
  27. <scope>import</scope>
  28. </dependency>
  29. </dependencies>
  30. </dependencyManagement>
  31. <dependencies>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-web</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-actuator</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework.cloud</groupId>
  42. <artifactId>spring-cloud-starter-config</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.cloud</groupId>
  46. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.cloud</groupId>
  50. <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.springframework.cloud</groupId>
  54. <artifactId>spring-cloud-starter-openfeign</artifactId>
  55. </dependency>
  56. </dependencies>
  57. <build>
  58. <plugins>
  59. <plugin>
  60. <groupId>org.springframework.boot</groupId>
  61. <artifactId>spring-boot-maven-plugin</artifactId>
  62. </plugin>
  63. </plugins>
  64. </build>
  65. </project>

application.properties配置:

spring.application.name=TestClient

server.port=7001

server.serviceName=TestServer

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

TestServer.ribbon.eureka.enabled=true
TestServer.ribbon.ServerListRefreshInterval=5

#TestServer.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.DynamicServerListLoadBalancer
#TestServer.ribbon.NIWSServerListClassName=com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList

eureka.client.register-with-eureka - false 表示不将自身注册成为service server。
eureka.client.fetch-registry - true表示从eureka server上获取服务列表。
eureka.client.serviceUrl.defaultZone - 设置eureka server的访问地址。

TestServer.ribbon.eureka.enabled - 表示是否对TestServer服务开启ribbon组件。
TestServer.ribbon.ServerListRefreshInterval - 表示对TestServer服务开启ribbon组件后,从eureka server上获取最新服务可访问地址的时间间隔。

下面分别以RibbonClient和FeignClient两种形式给出示例代码:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  7. import org.springframework.cloud.netflix.ribbon.RibbonClient;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.client.RestTemplate;
  12. @EnableDiscoveryClient
  13. @SpringBootApplication
  14. @RestController
  15. @RibbonClient(name = "${server.serviceName}", configuration = MyConfiguration.class)
  16. public class ClientApp {
  17. @Value("${server.serviceName}")
  18. private String serviceName;
  19. @LoadBalanced
  20. @Bean
  21. RestTemplate restTemplate() {
  22. return new RestTemplate();
  23. }
  24. @Autowired
  25. RestTemplate restTemplate;
  26. @RequestMapping("/hi")
  27. public String hi() {
  28. String greeting = this.restTemplate.getForObject("http://" + serviceName + "/base/message", String.class);
  29. return String.format("%s!", greeting);
  30. }
  31. public static void main(String[] args) {
  32. SpringApplication.run(ClientApp.class, args);
  33. }
  34. }
  35. import org.springframework.beans.factory.annotation.Autowired;
  36. import org.springframework.beans.factory.annotation.Value;
  37. import org.springframework.boot.SpringApplication;
  38. import org.springframework.boot.autoconfigure.SpringBootApplication;
  39. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  40. import org.springframework.cloud.netflix.ribbon.RibbonClient;
  41. import org.springframework.cloud.openfeign.EnableFeignClients;
  42. import org.springframework.cloud.openfeign.FeignClient;
  43. import org.springframework.web.bind.annotation.RequestMapping;
  44. import org.springframework.web.bind.annotation.RequestMethod;
  45. import org.springframework.web.bind.annotation.RestController;
  46. @EnableDiscoveryClient
  47. @SpringBootApplication
  48. @RestController
  49. @EnableFeignClients
  50. @RibbonClient(name = "${server.serviceName}", configuration = MyConfiguration.class)
  51. public class FeignClientApp {
  52. @Value("${server.serviceName}")
  53. private String serviceName;
  54. @Autowired
  55. private MessageClient client;
  56. @RequestMapping("/hihi")
  57. public String message() {
  58. return client.message();
  59. }
  60. @FeignClient(name = "${server.serviceName}")
  61. interface MessageClient {
  62. @RequestMapping(value = "/base/message", method = RequestMethod.GET)
  63. String message();
  64. }
  65. public static void main(String[] args) {
  66. SpringApplication.run(FeignClientApp.class, args);
  67. }
  68. }
  69. import org.springframework.beans.factory.annotation.Autowired;
  70. import org.springframework.context.annotation.Bean;
  71. import com.netflix.client.config.IClientConfig;
  72. import com.netflix.loadbalancer.AvailabilityFilteringRule;
  73. import com.netflix.loadbalancer.IPing;
  74. import com.netflix.loadbalancer.IRule;
  75. import com.netflix.loadbalancer.PingUrl;
  76. public class MyConfiguration {
  77. @Autowired
  78. IClientConfig ribbonClientConfig;
  79. @Bean
  80. public IPing ribbonPing(IClientConfig config) {
  81. return new PingUrl(false, "/base/home");
  82. }
  83. @Bean
  84. public IRule ribbonRule(IClientConfig config) {
  85. return new AvailabilityFilteringRule();
  86. }
  87. }

通过以下两个地址,就可以测试一下代码运行结果:

http://localhost:7001/hihi
http://localhost:7001/hi

另外,下表为Spring Cloud Netflix提供给Ribbon的默认值:














































Bean Type Bean Name Class Name

IClientConfig

ribbonClientConfig

DefaultClientConfigImpl

IRule

ribbonRule

ZoneAvoidanceRule

IPing

ribbonPing

DummyPing

ServerList<Server>

ribbonServerList

ConfigurationBasedServerList

ServerListFilter<Server>

ribbonServerListFilter

ZonePreferenceServerListFilter

ILoadBalancer

ribbonLoadBalancer

ZoneAwareLoadBalancer

ServerListUpdater

ribbonServerListUpdater

PollingServerListUpdater

参考文档

Client Side Load Balancer: Ribbon
Spring Cloud Netflix Eureka - The Hidden Manual
Multi-version Service Discovery using Spring Cloud Netflix Eureka and Ribbon
Spring Cloud Series - Microservices Registration and Discovery using Spring Cloud, Eureka, Ribbon and Feign
Microservice Registration and Discovery with Spring Cloud and Netflix’s Eureka
Client Side Load Balancing with Ribbon and Spring Cloud

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读

    相关 springcloud服务-项目

    前言:      乐优商城这个视频还可以,于是拿来练练手,我对着视频搭环境一直在service服务模块卡住了,注册中心和网关可以启动,服务模块却一直启动不了,报各种奇怪的错,

    相关 SpringCloud服务框架

    一、微服务架构 1.1什么是分布式 不同模块部署在不同服务器上 作用:分布式解决网站高并发带来问题 1.2什么是集群 多台服务器部署相同应用构成一个集群