1、创建Eureka(服务注册中心)
1.1 application.properties
server.port=8761 #eureka实例主机名 eureka.instance.hostname=eureka #不把自己注册到eureka上 eureka.client.register-with-eureka=false #不从eureka上获取注册信息 eureka.client.fetch-registry=false #key:defaultZone,value:http://localhost:8761/eureka eureka.client.service-url.defaultZone=http://localhost:8761/eureka
1.2 @EnableEurekaServer 启动
@EnableEurekaServer @SpringBootApplication public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
1.3 访问:http://localhost:8081/
2、创建服务提供者
1、application.properties
server.port=8082 spring.application.name=provider #注册服务的时候使用ip进行注册 eureka.instance.prefer-ip-address=true eureka.client.service-url.defaultZone=http://localhost:8761/eureka
2、创建controller
@RestController public class TestController { @GetMapping("hellow") public String hellow(){ return "hellow"; } }
3、启动(可以改变端口,启动多个provider)
@SpringBootApplication public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
4、Application就是我们配置的名字
3、创建服务消费者
3.1 application.properties
server.port=8084 spring.application.name=consumer #注册服务的时候使用ip进行注册 eureka.instance.prefer-ip-address=true eureka.client.service-url.defaultZone=http://localhost:8761/eureka
3.2 controller
@RestController public class ConsumerController { @Autowired public RestTemplate restTemplate; @GetMapping("hellow") public String consumerhellow(){ String forObject = restTemplate.getForObject("http://PROVIDER/hellow", String.class); //通过http来访问provider的 return "consumer"+forObject; } }
3.3 @EnableDiscoveryClient 和 RestTemplate ,启动
@EnableDiscoveryClient //开启服务发现功能 @SpringBootApplication public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } @LoadBalanced //使用负载均衡机制 @Bean //注册RestTemplate public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); return restTemplate; } }