服务提供者和消费者
一个是服务提供者,一个服务消费者
user-service
- pom.xml添加依赖
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- application.yml配置文件
server:
port: 9001
spring:
application:
name: user-service
eureka:
instance:
hostname: localhost
#开启ip注册
prefer-ip-address: true
client:
#默认值是true,是否将自己注册到注册中心
register-with-eureka: true
#默认值是true,是否从注册中心拉取服务
fetch-registry: true
#注册中信对外暴露的注册中心地址
service-url:
defaultZone: http://localhost:8761/eureka/
- 控制层代码
@RestController
public class UserController {
@GetMapping(value = "/provider/test")
public String test(){
return "---我是用户服务提供者---";
}
}
启动服务者访问 http://localhost:9001/provider/test
user-consumer
- pom.xml添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- application.ymal配置文件
server:
port: 9002
spring:
application:
name: user-consumer
eureka:
instance:
hostname: localhost
#开启ip注册
prefer-ip-address: true
client:
#默认值是true,是否将自己注册到注册中心
register-with-eureka: true
#默认值是true,是否从注册中心拉取服务
fetch-registry: true
#注册中信对外暴露的注册中心地址
service-url:
defaultZone: http://localhost:8761/eureka/
- 配置RestTemplate
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率,提供了不同的请求方试的接口供开发者使用
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- 控制层代码
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
private static final String URL = "http://localhost:9001";
@GetMapping(value = "/consumer/test")
public String getString(){
String str = restTemplate.getForObject(URL + "/provider/test", String.class);
return "服务消费者调用服务提供者:" + str;
}
}
启动消费者访问 http://localhost:9002/consumer/test
DiscoveryClient
服务消费使用了restTemplate远程调用了服务提供者,我们只需要知道服务的地址以及返回值类型,就可以实现远程访问。springcloud中有一个类提供的api可以获取服务列表,服务地址,端口,它就是DiscoveryClient类
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping(value = "/discoveryClient")
public String discoveryClientTest() {
//获取服务列表
List<String> services = discoveryClient.getServices();
System.out.println("所有服务列表:" + services);
//获取服务实例
List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
ServiceInstance serviceInstance = instances.get(0);
//拼接请求的地址
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort();
System.out.println("请求的url:" + url);
return url;
}
}