初识spring-cloud-ribbon

版本声明
组件 版本
spring-boot 2.1.3.RELEASE
spring-cloud-starter-eureka 1.3.4.RELEASE
spring-cloud-dependencies Finchley.RELEASE
spring-cloud-starter-netflix-ribbon 2.0.2.RELEASE

主要依赖引入:

    
		
			org.springframework.cloud
			spring-cloud-starter-eureka
			1.3.4.RELEASE
		

		
			org.springframework.cloud
			spring-cloud-starter-netflix-ribbon
			2.0.2.RELEASE
		

	

	
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				Finchley.RELEASE
				pom
				import
			
		
	

实例化RestTemplate:

package com.sc.consumerribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerRibbonApplication {

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

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
}

控制器:

package com.sc.consumerribbon.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    private String serviceName = "http://HELLO-SERVICE/hello/";

    @GetMapping("/ribbon-consumer")
    public String helloConsumer(){
        return restTemplate.getForEntity(this.serviceName, String.class).getBody();
    }

}

application.preperties配置:

spring.application.name=ribbon-consumer
server.port=9000
eureka.client.service-url.defaultZone=http://peer1:12451/eureka,http://peer2:12452/eureka
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=true

运行:java -jar ./consumer-ribbon-0.0.1-SNAPSHOT.jar

观察eureka面板:

初识spring-cloud-ribbon_第1张图片

调用接口,发现的确是轮询hello-service服务:

初识spring-cloud-ribbon_第2张图片

重点观察ribbon-consumer输出:

初识spring-cloud-ribbon_第3张图片

坑:{"timestamp":"2019-04-01T02:28:34.933+0000","status":500,"error":"Internal Server Error","message":"I/O error on GET request for \"http://HELLO-SERVICE/hello/\": HELLO-SERVICE; nested exception is java.net.UnknownHostException: HELLO-SERVICE","path":"/ribbon-consumer/"}

因为之前在pom里引用的是:

    
		org.springframework.cloud
		spring-cloud-starter-ribbon
		1.3.4.RELEASE
	

把它改为如下就可以:

    
		org.springframework.cloud
		spring-cloud-starter-netflix-ribbon
		2.0.2.RELEASE
	

 

你可能感兴趣的:(spring-cloud,Spring-boot,spring-boot,spring-cloud,java)