合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
构建步骤如下: **1. 构建消费端模块:cloud-comsumer-order80** **2. 在当前模块的`pom.xml`中添加 eureka-client 依赖** ```xml <dependencies> <!-- eureka-client 引入了ribbon --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> ... </dependencies> ``` **3. 当前模块的`resources/application.yml`** ```yml server: port: 80 spring: application: name: cloud-comsumer-order eureka: client: service-url: #将当前模块注册到三个注册中心中 defaultZone: http://www.eureka7001.com:7001/eureka/,http://www.eureka7002.com:7002/eureka/,http://www.eureka7003.com:7003/eureka/ instance: instance-id: ${project.artifactId} prefer-ip-address: true lease-renewal-interval-in-seconds: 1 lease-expiration-duration-in-seconds: 2 ####actuator#### info: app.name: ${spring.application.name} company.name: www.atguigu.com build.artifactId: ${project.artifactId} build.version: ${project.version} #要访问的微服务地址 #地址写的是服务端 spring.application.name 配置 provider: payment: name: cloud-payment-service url: http://${provider.payment.name}/ ``` **4. 在当前模块配置`RestTemplate`组件** ```java @Configuration public class ApplicationContextConfig { @Bean @LoadBalanced //该注解默认的负载均衡策略是轮询策略 public RestTemplate getRestTemplate() { return new RestTemplate(); } } ``` **5. 在当前模块调用服务端** ```java @RestController @RequestMapping("/order") public class OrderController { @Value("${provider.payment.url}") private String PROVIDER_URL; @Resource private RestTemplate restTemplate; @GetMapping("/idport") public String idPort() { //调用服务端 return restTemplate.getForObject(PROVIDER_URL + "/payment/idport", String.class); } } ``` **6. 在当前模块的启动类中添加注解`@EnableEurekaClient`** ```java @SpringBootApplication @EnableEurekaClient public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class,args); } } ``` **7. 测试负载均衡效果** (1)启动三个Eureka注册中心。 ``` cloud-eureka-server7001 cloud-eureka-server7002 cloud-eureka-server7003 ``` (2)启动2个服务端。 ``` cloud-provider-payment8001 cloud-provider-payment8002 ``` (3)启动当前模块。 ``` cloud-comsumer-order80 ``` 不断刷新当前模块的地址 http://localhost:80/order/idport ,其效果是消费端按照轮询的方式调用两个服务端。 ![](https://img.kancloud.cn/46/35/4635a85ba72565212e770d5fe93b3698_1148x161.gif)