前篇文章写的是spring cloud service,服务有了,那么下面就是怎么来调用服务了。
其实,spring cloud的请求也是基于http的,不过是http2的协议。深层次的实现方案暂不讨论,先解决应用性问题。
1.pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
2.application.yml
server:
port: 9903
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
3.启动函数
@SpringBootApplication
@EnableEurekaClient
public class ClientApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class,args);
}
}
这里用 RestTemplate作为 client .@LoadBalanced 这个注解的作用是用来做负载均衡的,里面会有算法实现
4.client 实现
@RestController
@RequestMapping(value = "user")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping(value = "test")
public String index(){
return restTemplate.getForObject("http://example-service/user",String.class);
}
}
5.测试效果