项目下载地址 https://github.com/huangDevelop/springcloud
一、新建项目springcloud-consumer,复制springcloud-provider,修改名称为springcloud-provider-02(端口8082),springcloud-provider-03(端口8083)
二、负载均衡
a. ribbon负载均衡
pom.xml
<!-- ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
配置文件
server:
port: 82
spring:
application:
name: ribbon-consumer
eureka:
instance:
hostname: 192.168.0.230
port: 8761
client:
service-url:
default-zone: http://${eureka.instance.hostname}:${eureka.instance.port}/eureka/
启动类
@SpringBootApplication
public class RibbonApplication {
/**
* 开启负载均衡
* @LoadBalanced
* @return
*/
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
创建访问类
@RestController
public class RibbonController {
@Autowired
private RestTemplate restTemplate;
/**
* 指定调用服务提供者(eureka-provider-dev)
*/
@RequestMapping(value = "/ribbon")
public String hello() {
return restTemplate.getForEntity("http://eureka-provider-dev/", String.class).getBody();
}
}
测试
![](https://img2018.cnblogs.com/blog/732626/201901/732626-20190111112248671-1977599029.png)
访问消费者接口 http://192.168.0.230:82/ribbon
ribbon负载均衡处理成功
b.fiegn负载均衡
pom.xml
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
配置文件
server:
port: 81
spring:
application:
name: feign-consumer
eureka:
instance:
hostname: 192.168.0.230
port: 8761
client:
service-url:
default-zone: http://${eureka.instance.hostname}:${eureka.instance.port}/eureka/
启动类
@EnableFeignClients //声明feign客户端
@SpringBootApplication
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
创建feign接口
/**
* 指定调用服务提供者(eureka-provider-dev)
*/
@FeignClient("eureka-provider-dev")
public interface FeignConsumer {
/**
* 访问服务提供者方法
* @return
*/
@RequestMapping("/")
String writePort();
}
创建访问类
@RestController
public class FeignController {
@Autowired
private FeignConsumer feignConsumer;
@RequestMapping(value = "/feign")
public String hello() {
return feignConsumer.writePort();
}
}
测试
启动成功,注册中心收到信号
访问消费者接口 http://192.168.0.230:81/feign
feign负载均衡处理成功
c.eureka负载均衡
配置文件
server:
port: 80
启动类
@SpringBootApplication
public class EurekaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
创建访问类
@RestController
public class EurekaController {
@Autowired
private EurekaClient client;
@RequestMapping("/")
public String hello() {
InstanceInfo instanceInfo = client.getNextServerFromEureka("eureka-provider-dev", false);
return instanceInfo.getHomePageUrl();
}
}
测试
![](https://img2018.cnblogs.com/blog/732626/201901/732626-20190111115136681-845284940.png)
![](https://img2018.cnblogs.com/blog/732626/201901/732626-20190111114901647-1291852610.png)
eureka负载均衡处理成功