版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuxiaoxiaosmile/article/details/82971213
1. 依赖
1)负载均衡包spring-cloud-starter-ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
#还包括“SpringBoot 服务注册”中的两个依赖:
#spring-boot-starter-actuator
#spring-cloud-starter-consul-discovery
2. SpringBoot入口类中添加代码如下:
package com.ethan.example.client;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@EnableDiscoveryClient //使用服务注册和发现
@SpringBootApplication
public class Application {
@Bean
@LoadBalanced //RestTemplate实例使用服务发现与负载均衡
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args); //重要
}
}
3. 使用示例
package com.ethan.example.client.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@Api(description = "Test Service Found")
@RestController
@RequestMapping("/test")
public class RestTemplateServiceFundController {
Logger logger = LoggerFactory.getLogger(RestTemplateServiceFundController.class);
@Autowired
private RestTemplate restTemplate;
@GetMapping("/find")
@ApiOperation(value = "Make Service Found")
public String makeFound() {
logger.info("test service found begin...");
//URL中使用服务名称example代替IP,第一个example是服务名称,第二个example是api路径
String result = restTemplate.getForObject("http://example/example/project/hello", String.class);
return result;
}
}