每一个注册在微服务中的服务,既是服务提供者也是服务消费者。
我们创建一个Eureka-consumer项目作为服务消费者来消费Eureka-client。
pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</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>
application.properties:
spring.application.name=eureka-consumer
server.port=2101
eureka.client.serviceUrl.defaultZone=http://root:root@eureka1:1001/eureka/,http://root:root@eureka2:1002/eureka/
logging.file=${spring.application.name}.log
创建项目启动类:
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
RestTemplate:用来发起REST请求
创建消费者接口类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class DcController {
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
RestTemplate restTemplate;
@GetMapping("/consumer")
public String dc() {
ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client");
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
System.out.println(url);
return restTemplate.getForObject(url, String.class);
}
}
注入了
LoadBalancerClient
和
RestTemplate
,并在
/consumer
接口的实现中,先通过
loadBalancerClient
的
choose
函数来负载均衡的选出一个
eureka-client
的服务实例,这个服务实例的基本信息存储在
ServiceInstance
中,然后通过这些对象中的信息拼接出访问
/dc
接口的详细地址,最后再利用
RestTemplate
对象实现对服务提供者接口的调用。
分别启动注册中心、服务提供者、服务消费者项目,然后访问http://localhost:2101/consumer