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;
}
}