🥝:如何实现远程调用,小编将全面介绍springcloud如何实现远程调用,最后将会提供一个企业的普遍实现方式。
一、使用RestTemplate实现
🥥:RestTemplate是springcloud框架原生的实现远程调用的一个类,因此使用RestTemplate不需要导入额外的依赖。
1、在启动类创建获取RestTemplate
// 远程调用
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
2、在使用服务类中注入并且调用
private final RestTemplate restTemplate;
...
ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(
"http://127.0.0.1:8081/items?ids={ids}",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<ItemDTO>>() {
},
StrUtil.join(",", itemIds)
);
3、获取返回体
List<ItemDTO> items = response.getBody();
注意:服务的实例获取可以使用下面的方式
// 注入DiscoveryClient
private final DiscoveryClient discoveryClient;
...
// 获取服务实例
List<ServiceInstance> instances = discoveryClient.getInstances("item-service");
ServiceInstance instance = instances.get(RandomUtil.randomInt(instances.size()));
二、使用openfeign实现远程调用
1、导入依赖
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--loadbalancer负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
2、创建openfeign客户端
@FeignClient(value = "item-service")
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemById(@RequestParam("ids") Collection<Long> ids);
}
3、注入openfeign客户端并使用
private final ItemClient itemClient;
...
List<ItemDTO> items = itemClient.queryItemById(itemIds);
4、fegin连接池使用
导入依赖
<!--openfeign连接池-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
配置yaml文件
feign:
okhttp:
enabled: true
三、企业级别实现远程调用
注意:在微服务项目里面,可以将fegin客户端抽成单独的模块
目录结构
注意:dto存放需要dto文件、client存放feign客户端、config存放配置文件
1、hm-api的pom.xml文件
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--loadbalancer负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!--okhttp连接池-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
2、在需要使用远程调用的模块直接导入hm-api坐标
<!--hm-api-->
<dependency>
<groupId>com.heima</groupId>
<artifactId>hm-api</artifactId>
<version>1.0.0</version>
</dependency>
3、feign日志记录 在config文件配置日志记录bean
package com.hmall.api.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
public class DefaultFeignConfig {
@Bean
public Logger.Level feignLogLevel() {
return Logger.Level.NONE;
}
}
在单一的客户端使用
configuration = DefaultFeignConfig.class
...
@FeignClient(value = "item-service", configuration = DefaultFeignConfig.class)
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemById(@RequestParam("ids") Collection<Long> ids);
}
全局配置,需要在启动类配置
@EnableFeignClients(clients = ItemClient.class, defaultConfiguration = DefaultFeignConfig.class)
资料链接:pan.baidu.com/s/11P-ci8NY… 提取码:k5oi