ribbon + spring-retry容错机制记录

导入依赖,pom.xml

		<parent>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-parent</artifactId>
			<version>2.3.9.RELEASE</version>
			<relativePath/> 
		</parent>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.springframework.retry</groupId>
		    <artifactId>spring-retry</artifactId>
		</dependency>

配置,application.properties,不使用Eureka,直接配置调用的IP

ribbon.eureka.enabled=false
mytestapp.ribbon.listOfServers=192.168.1.246:8081,192.168.1.36:8083

## timeout,RestTemplate负责构建
#ribbon.ConnectTimeout=5000
#ribbon.ReadTimeout=30000

## concurrent
ribbon.MaxTotalConnections=200
ribbon.MaxConnectionsPerHost=100

## spring-retry

spring.cloud.loadbalancer.retry.enabled=true
mytestapp.ribbon.maxAutoRetries=1
mytestapp.ribbon.maxAutoRetriesNextServer=2
mytestapp.ribbon.okToRetryOnAllOperations=true
mytestapp.ribbon.retryableStatusCodes=500,404,502

debug=true

新增RestTemplate 对象,添加注解@LoadBalanced,整合Ribbon

@Configuration
public class RestTemplateConfiguration {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
    	HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(500);
        httpRequestFactory.setReadTimeout(2000);
        return new RestTemplate(httpRequestFactory);
    }
}

测试类

@RestController
public class TestController {
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping("/test/lb")
	public String loadBalanced() {
		String result = restTemplate.getForObject("http://mytestapp/hello", String.class);
		return result;
	}
	
	@GetMapping("/test/lb404")
	public String loadBalanced404() {
		String result = restTemplate.getForObject("http://mytestapp/hello222", String.class);
		return result;
	}

}

启动类

@SpringBootApplication
public class SpringRetryDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringRetryDemoApplication.class, args);
	}

}

测试

  1. 启动调用服务
    ribbon + spring-retry容错机制记录_第1张图片
    ribbon + spring-retry容错机制记录_第2张图片
  2. 测试/test/lb
    ribbon + spring-retry容错机制记录_第3张图片
    正常
  3. 测试/test/lb404
    ribbon + spring-retry容错机制记录_第4张图片
    两台app都有调用
    ribbon + spring-retry容错机制记录_第5张图片
    ribbon + spring-retry容错机制记录_第6张图片

你可能感兴趣的:(ribbon,spring,cloud)