//准备工作
/**已经将名为SPRINGCLOUD-PROVIDER-DEPT的服务注册到了由
http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ 三个eureka注册中心组成的集群上面了。
*/
1.导包 在客户端导入 spring-cloud-starter-ribbon、spring-cloud-starter-eureka(注意这是客户端的包)
<!--eureka需要的包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<!--ribbon-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
2.配置 配置客户端不在eureka中注册,以及服务注册地址
//是三个注册中心的地址
server:
port: 80
eureka:
client:
register-with-eureka: false #不在eureka中注册自己
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
eureka: client: register-with-eureka: false #不在eureka中注册自己 service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
3.在启动类中添加启动eureka的注解@EnableEurekaClient
4.配置能够实现负载均衡的RestTemplate
给RestTemplate 添加 @LoadBalanced注解 即可
package com.zyh.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConfigBean {
// 配置负载均衡实现restTemplage
@LoadBalanced //Ribbon
@Bean
public RestTemplate getRestTemplate( ){
return new RestTemplate();
}
}
5.在controller中调用
SPRINGCLOUD-PROVIDER-DEPT 是调用的服务名
@RestController
@RequestMapping("/consumer")
public class DeptConsumerController {
@Autowired
private RestTemplate restTemplate;//提供多种访问远程服务接口的方法
private final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT/";
@PostMapping("/saveDept")
public Boolean saveDept( @RequestBody DeptBo deptBo){
return restTemplate.postForObject(REST_URL_PREFIX + "/dept/addDept",deptBo, Boolean.class);
}
}
待完善