第一步创建工程
1、选择File,然后new 再然后Project,选择Spring Initializr然后下一步
2、填写项目信息,然后下一步
3、选择依赖 Spring Cloud Discovery 然后选择Eureka Discovery Client ,然后下一步
4、创建项目存储位置及名称
第二步,创建BeanConfiguration的类,创建RestTemplate
1 package com.ssc.consumer; 2 3 import org.springframework.cloud.client.loadbalancer.LoadBalanced; 4 import org.springframework.context.annotation.Bean; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.web.bind.annotation.GetMapping; 7 import org.springframework.web.client.RestOperations; 8 import org.springframework.web.client.RestTemplate; 9 10 @Configuration 11 public class BeanConfiguration { 12 @Bean 13 @LoadBalanced 14 public RestTemplate getRestTemplate(){ 15 return new RestTemplate(); 16 } 17 18 19 }
第三步写调用接口
1 package com.ssc.consumer; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.GetMapping; 5 import org.springframework.web.bind.annotation.RestController; 6 import org.springframework.web.client.RestTemplate; 7 8 @RestController 9 public class ConsumerController { 10 @Autowired 11 private RestTemplate restTemplate;
//直接调用 12 @GetMapping("/consumer/callHello") 13 public String callHello(){ 14 return restTemplate.getForObject("http://localhost:8055/user/hello",String.class); 15 } 16 //通过Eureka调用 17 @GetMapping("/consumer/callHello2") 18 public String callHello2(){ 19 return restTemplate.getForObject("http://eureka-user-provide/user/hello",String.class); 20 } 21 22 }
第四步、添加application.yml文件
1 spring: 2 application: 3 name: eureka-user-consumer 4 server: 5 port: 8056 6 eureka: 7 client: 8 service-url: 9 defaultZone: http://localhost:8761/eureka
第五步、启动程序,访问 http://localhost:8056/consumer/callHello2查看效果