一、准备工作,eclipse运行两个实例
1、修改 eurekaclient1 中 application.yml 文件
server: port: 8762spring: application: name: eurekaclienteureka: instance: instance-id: eurekaclient1 appname: ${spring.application.name} client: serviceUrl: defaultZone: http://localhost:8761/eureka/
2、同级目录下复制一份 application.yml 文件 命名为 application-two.yml
server: port: 8763spring: application: name: eurekaclienteureka: instance: instance-id: eurekaclient2 appname: ${spring.application.name} client: serviceUrl: defaultZone: http://localhost:8761/eureka/
3、启动 EurekaClientApplication.java (第一个实例)
4、启动 EurekaClientApplication.java (第二个实例)
右键->Run As -> Run Configurations.. ->Arguments-> Programe Arguments 输入 --spring.profiles.active=two 点击 run
5、查看 多个实例
6、1
二、新建maven 工程 service-ribbon (服务消费者 )
1、修改pom.xml
4.0.0 wg service-ribbon 0.0.1-SNAPSHOT jar service-ribbon http://maven.apache.org UTF-8 UTF-8 Greenwich.RELEASE 1.8 org.springframework.boot spring-boot-starter-parent 2.1.1.RELEASE org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-ribbon junit junit test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import
2、创建启动类(位于所有类的上级包下)
package wg;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.context.annotation.Bean;import org.springframework.web.client.RestTemplate;@SpringBootApplication@EnableEurekaClient@EnableDiscoveryClientpublic class ServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run( ServiceRibbonApplication.class, args ); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }}
3、创建application.yml
server: port: 8764spring: application: name: service-ribboneureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
4、创建service
package wg.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;@Servicepublic class HelloService { @Autowired RestTemplate restTemplate; public String helloService() { return restTemplate.getForObject("http://EUREKACLIENT/",String.class); }}
5、创建controller
package wg.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import wg.service.HelloService;@RestControllerpublic class HelloController { @Autowired HelloService helloService; @RequestMapping(value = "/hello") public String hi() { return helloService.helloService( ); }}
6、启动项目,多次访问:
交替出现
7、访问
项目结构:
上一篇:
下一篇: