pom.xml部分
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Finchley.RC1</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.retry/spring-retry --> <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </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>
启动类
此类用于ribbon客户端请求
@Bean @LoadBalanced public RestTemplate restTemplate() { HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(); return new RestTemplate(httpRequestFactory); }
客户端使用ribbon请求服务 下面用的方式为serviceId根据在eureka中服务名来访问
@RequestMapping(value = "/ribbon-consumer",method = RequestMethod.GET) public String helloController() { return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody(); }
调用HELLO-SERVICE服务中hello方法 在生产环境中大部分公司都采用集群的方式这样一个节点宕掉还有别的节点继续提供服务
本次事例为集群模式下载有两个HELLO-SERVICE
我们停掉一个继续用ribbon-consumer来访问大家就会发现页面已经开始报错了
这个错误原因是因为虽然我们的节点死掉了 但是这是后eureka并没有将这个节点删除
这怎么办呢 我们只需要开启ribbon的重试功能就好了 此功能作用为当访问到死掉的节点可以将本次请求转发到另一节点去处理
下面贴出application.properties文件ribbon重试部分
#开启ribbon重试 spring.cloud.loadbalancer.retry.enabled=true #请求连接的超时时间 HELLO-SERVICE.ribbon.ConnectTimeout=250 #请求处理的超时时间 HELLO-SERVICE.ribbon.ReadTimeout=1000 #对所有操作请求都进行重试 HELLO-SERVICE.ribbon.OkToRetryOnAllOperations=true #切换实例的重试次数 HELLO-SERVICE.ribbon.MaxAutoRetriesNextServer=2 #对当前实例的重试次数 HELLO-SERVICE.ribbon.MaxAutoRetries=1其中HELLO-SERVICE为服务名