Spring Cloud 之 Ribbon,Spring RestTemplate 调用服务

Eureka Server 集群基础上,使用Spring RestTemplate,结合Ribbon功能进行服务调用,使用方式非常简单。

1、在主项目中新建一个模块,eurekaclient,maven依赖,

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</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>

2、application.yml配置文件,

spring:
  application:
    name: eurekaclient
server:
  port: 8080
  shutdown: graceful
eureka:
  client:
    service-url:
      defaultZone: http://peer1:8761/eureka/

3、在启动类中定义RestTemplate,通过Spring Cloud的@LoadBalanced注解可以支持Ribbon开启负载均衡。

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

4、在logservice服务中开发一个接口,供eurekaclient服务调用,

@RestController
@RequestMapping("log")
public class LogController {

    @GetMapping("logInfo")
    public String logInfo(String logInfo) {
        System.out.println(logInfo);
        return logInfo;
    }

}

5、在eurekaclient中定义一个Service类,通过@Component注解添加到容器中,使用restTemplate调用logservice服务,

@Component
public class LogServiceClient {

    @Autowired
    private RestTemplate restTemplate;

    public String logInfo(String logInfo) {
        return restTemplate.getForObject("http://logservice/log/logInfo?logInfo="+logInfo, String.class);
    }

}

在eurekaclient中定义接口,调用步骤5中的Service类的logInfo方法,

@RestController
@RequestMapping("client")
public class TestController {
    @Autowired
    private LogServiceClient logServiceClient;

    @GetMapping("getClientInfo")
    public String getClientInfo() {
        String info = "log info";
        return logServiceClient.logInfo(info);
    }
}

6、浏览器输入eurekaclient中定义的接口地址,http://localhost:8080/client/getClientInfo

7、测试Ribbon负载均衡也很方便,只需要启动logservice的多个实例

猜你喜欢

转载自blog.csdn.net/suoyx/article/details/114102636