SpringCloud服务调用
文章目录
一、服务调用
微服务之间的调用(普通方式)
1、通过DiscoveryClient的getInstances(服务名)获取服务的实例列表
2、获取实例列表中的某一个服务
3、利用实例中的getUri()方法获取服务的uri
4、利用RestTemplate的远程调用方法调用其他微服务
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{id}")
public String test(@PathVariable("id") String id){
ServiceInstance serviceInstance = discoveryClient
.getInstances("cloud-provider")
.get(0);
return restTemplate.getForObject(
serviceInstance.getUri()+"/msg/{id}",
String.class, id
);
}
}
二、RestTemplate
简介
传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,RestTemplate。
API
API | 作用 |
---|---|
getForEntity(url,返回类型的Class) | 以get方式发送请求返回值为 |
getForObject(url,返回类型的Class) | 以get方式发送请求返回值为json |
postForEntity(url,消息体,返回类型的Class) | 以post方式发送请求 |
postForObject(url,消息体,返回类型的Class) | 以post方式发送请求 |
delete(url,占位符) | 发送delete请求 |
put(url,传递的实体) | 发送put请求 |
三、Ribbon简介
Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。
四、Ribbon负载均衡使用方式
1、引入依赖
在Eureka和Nacos服务发现依赖中已经引入依赖:
2、使用方式:
通常配合RestTemplate使用(调用端-消费者使用)
在RestTemplate的bean上添加注解@LoadBalanced即可
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
五、OpenFeign组件简介
Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解,即可像RestTemplate那样调用其他微服务。
六、OpenFeign组件使用方式
1、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、创建接口加注解
@FeignClient(value = "cloud-provider")
public interface ProviderService {
@GetMapping("/msg/{id}")
String msg(@PathVariable("id") String id);
}
3、在启动类上添加注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class CloudConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConsumerApplication.class, args);
}
}
4、编写接口方法
@GetMapping("/msg/{id}")
String msg(@PathVariable("id") String id);