spring-cloud-2.x(服務消費者)
阿新 • • 發佈:2019-01-11
static nap 負載均衡 eth sta stat 調用服務 inter ren
一、新建項目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(服務消費者)