提供者配置yml:
server:
port: 3001
eureka:
instance:
preferIpAddress: true
client:
serviceUrl:
defaultZone: http://localhost:3000/eureka ## 注册到 eureka
spring:
application:
name: single-provider ## 应用程序名称,消费者调用的时候有用
创建一个controller
Slf4j
@RestController
public class ProviderController {
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value = "/hello")
public String hello(){
List<String> services = discoveryClient.getServices();
for(String s : services){
log.info(s);
}
return "hello spring cloud!";
}
}
消费者配置yml:
server:
port: 3002
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:3000/eureka ## 注册到 eureka
instance:
preferIpAddress: true
spring:
application:
name: single-customer
消费者有2种消费方式:
一种是用 RestTemplate ,另外一种是用 FeignClient
配置类重写RestTemplate 方法:
@Configuration
public class CustomConfiguration {
@LoadBalanced // 表示用负载均衡策略请求服务提供者
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
用@FeignClient注解,注入single-provider应用的/hello请求对应的方法作为服务
@FeignClient("single-provider") // 注入single-provider应用的/hello 为服务
public interface IHelloService {
@RequestMapping(value = "/hello")
String hello();
}
用这个controller来调用服务:
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private IHelloService helloService;
private static final String applicationName = "single-provider";
@RequestMapping(value = "feignRequest")
public Object feignRequest(){
String s = helloService.hello();
return s;
}
@RequestMapping(value = "commonRequest")
public Object commonRequest(){
String url = "http://"+ applicationName +"/hello";
String s = restTemplate.getForObject(url,String.class);
return s;
}
}