spring-cloud-2.x(服务消费者)
Posted hl201211
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring-cloud-2.x(服务消费者)相关的知识,希望对你有一定的参考价值。
一、新建项目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();
}
}
测试
访问消费者接口 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();
}
}
测试
eureka负载均衡处理成功
以上是关于spring-cloud-2.x(服务消费者)的主要内容,如果未能解决你的问题,请参考以下文章
SpringCloud-创建服务消费者-Ribbon方式(附代码下载)