远程调用
RestTemplate
Spring提供了RestTemplate工具,可以方便的实现HTTP请求的发送。
-
注入
RestTemplate到Spring容器
-
通过构造函数注入到
Service层@RequiredArgsConstructor:创建包含必须初始化(final)的属性的构造函数
-
发起远程调用
public <T> ResponseEntity</T> exchange(
String url, // 请求路径
HttpMethod method, // 请求方式
@Nullable HttpEntity<?> requestEntity, // 请求实体,可以为空
Class<T> responseType, // 返回值类型
Map<String, ?> uriVariables // 请求参数,jdk11的写法
)// jdk8的Map写法
String joinedIds = CollUtil.join(itemIds, ",");
// 创建一个临时的可变 Map
Map<String, String> tempMap = new HashMap<>();
tempMap.put("ids", joinedIds);
// 创建一个不可变的 Map
Map<String, String> map = Collections.unmodifiableMap(tempMap);
(OpenFeign)[https://github.com/OpenFeign/feign]
是一个声明式的http客观端,是SpringCloud在Eureka公司开源的Feign基础上改造而来。
基于SpringMVC的常见注解,实现http请求的发送
-
引入依赖
<!--openFeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency> -
启动
OpenFeign使用
@EnableFeignClients注解@EnableFeignClients
@SpringBootApplication
public class Application {……} -
在
/client目录下新建ItemClient接口,编写FeignClient@FeignClient(value = "服务名,如item-service")
public interface ItemClient {
@GetMapping("路由,如/items")
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
} -
使用
FeignClient,实现远程调用List<ItemDTO> items = itemClient.queryItemByIds(List.of(1,2,3));
优化-连接池
Feign底层发起http请求,依赖于其它的框架。其底层支持的http客户端实现包括:
- HttpURLConnection:默认实现,不支持连接池
- Apache HttpClient :支持连接池
- OKHttp:支持连接池
-
引入依赖
<!--OK http 的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>