远程访问是开发的常用技术,一个应用能够访问其他应用的功能。Spring Boot 提供了多种远程访问的技术。基于 HTTP 协议的远程访问是支付最广泛的。Spring Boot3 提供了新的 HTTP 的访问能力,通过接口简化 HTTP 远程访问,类似 Feign 功能。Spring 包装了底层 HTTP 客户的访问细节。

SpringBoot 中定义接口提供 HTTP 服务。生成的代理对象实现此接口,代理对象实现 HTTP 的远程访问。需要理解:

  • @HttpExchange
  • WebClient

WebClient 特性:

我们想要调用其他系统提供的 HTTP 服务,通常可以使用 Spring 提供的 RestTemplate 来访问,RestTemplate 是 Spring 3 中引入的同步阻塞式 HTTP 客户端,因此存在一定性能瓶颈。Spring 官方在 Spring 5 中引入了 WebClient 作为非阻塞式 HTTP 客户端。

  • 非阻塞,异步请求
  • 它的响应式编程的基于 Reactor
  • 高并发,硬件资源少。
  • 支持 Java 8 lambdas 函数式编程

什么是异步非阻塞

理解:异步和同步,非阻塞和阻塞
上面都是针对对象不一样
异步和同步针对调度者,调用者发送请求,如果等待对方回应之后才去做其他事情,就是同步,如果发送请求之后不等着对方回应就去做其他事情就是异步
阻塞和非阻塞针对被调度者,被调度者收到请求后,做完请求任务之后才给出反馈就是阻塞,收到请求之后马上给出反馈然后去做事情,就是非阻塞

1 准备工作: 

1.安装 GsonFormat 插件,方便 json 和 Bean 的转换

2.介绍一个免费的、24h 在线的 Rest Http 服务,每月提供近 20 亿的请求,关键还是免费的、可公开访问的。

1.1 声明式 HTTP 远程服务  

需求: 访问 https://jsonplaceholder.typicode.com/   提供的 todos 服务。基于 RESTful 风格,添加新的 todo,修改 todo,修改 todo 中的 title,查询某个 todo。声明接口提供对象 https://jsonplaceholder.typicode.com/todos 服务的访问

创建新的 Spring Boot 项目 Lession18-HttpService, Maven 构建工具,JDK19。 Spring Web, Spring Reactive Web , Lombok 依赖。

step1:Maven 依赖 pom.xml

<dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
 </dependency>
 
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
 </dependency>
 <dependency>
  <groupId>io.projectreactor</groupId>
  <artifactId>reactor-test</artifactId>
  <scope>test</scope>
 </dependency>
</dependencies>

step2:声明 Todo 数据类

/**
 * 根据https://jsonplaceholder.typicode.com/todos/1 的结构创建的
 */
public class Todo {
  private int userId;
  private int id;
  private String title;
  private boolean completed;
 
  //省略 set , get方法
 
  public boolean getCompleted() {
    return completed;
  }
 
  public void setCompleted(boolean completed) {
    this.completed = completed;
  }
 
  @Override
  public String toString() {
    return "Todo{" +
        "userId=" + userId +
        ", id=" + id +
        ", title='" + title + '\'' +
        ", completed=" + completed +
        '}';
  }
}

step3:声明服务接口

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
//...
 
public interface TodoService {
 
   @GetExchange("/todos/{id}")
   Todo getTodoById(@PathVariable Integer id);
 
   @PostExchange(value = "/todos",accept = MediaType.APPLICATION_JSON_VALUE)
   Todo createTodo(@RequestBody  Todo newTodo);
 
   @PutExchange("/todos/{id}")
   ResponseEntity<Todo> modifyTodo(@PathVariable Integer id,@RequestBody Todo todo);
 
   @PatchExchange("/todos/{id}")
   HttpHeaders pathRequest(@PathVariable Integer id, @RequestParam String title);
 
 
   @DeleteExchange("/todos/{id}")
   void removeTodo(@PathVariable Integer id);
 
}
 

step4:创建 HTTP 服务代理对象

@Configuration(proxyBeanMethods = false)
public class HttpConfiguration {
 
  @Bean
  public TodoService requestService(){
    WebClient webClient = WebClient.builder().baseUrl("https://jsonplaceholder.typicode.com/").build();
    HttpServiceProxyFactory proxyFactory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient)).build();
    return proxyFactory.createClient(TodoService.class);
  }
}

step5:单元测试

@SpringBootTest
class HttpApplicationTests {
 
  @Resource
  private TodoService requestService;
 
  @Test
  void testQuery() {
    Todo todo = requestService.getTodoById(1);
    System.out.println("todo = " + todo);
  }
 
  @Test
  void testCreateTodo() {
    Todo todo = new Todo();
    todo.setId(1001);
    todo.setCompleted(true);
    todo.setTitle("录制视频");
    todo.setUserId(5001);
 
    Todo save = requestService.createTodo(todo);
    System.out.println(save);
  }
 
  @Test
  void testModifyTitle() {
    //org.springframework.http.HttpHeaders
    HttpHeaders entries = requestService.pathRequest(5, "homework");
    entries.forEach( (name,vals)->{
      System.out.println(name);
      vals.forEach(System.out::println);
      System.out.println("=========================");
    });
 
  }
 
  @Test
  void testModifyTodo() {
    Todo todo = new Todo();
    todo.setCompleted(true);
    todo.setTitle("录制视频!!!");
    todo.setUserId(5002);
    ResponseEntity<Todo> result = requestService.modifyTodo(2,todo);
    HttpStatusCode statusCode = result.getStatusCode();
    HttpHeaders headers = result.getHeaders();
    Todo modifyTodo = result.getBody();
 
    System.out.println("statusCode = " + statusCode);
    System.out.println("headers = " + headers);
    System.out.println("modifyTodo = " + modifyTodo);
 
  }
 
  @Test
  void testRemove() {
    requestService.removeTodo(2);
  }
}

1.2 Http 服务接口的方法定义

@HttpExchange 注解用于声明接口作为 HTTP 远程服务。在方法、类级别使用。通过注解属性以及方法的参数设置 HTTP 请求的细节。

快捷注解简化不同的请求方式

  • GetExchange
  • PostExchange
  • PutExchange
  • PatchExchange
  • DeleteExchange

@GetExchange 就是@HttpExchange 表示的 GET 请求方式

@HttpExchange(method = "GET")
public @interface GetExchange {
 
	@AliasFor(annotation = HttpExchange.class)
	String value() default "";
 
	@AliasFor(annotation = HttpExchange.class)
	String url() default "";
 
	@AliasFor(annotation = HttpExchange.class)
	String[] accept() default {};
 
}

作为 HTTP 服务接口中的方法允许使用的参数列表

参数说明
URI设置请求的 url,覆盖注解的 url 属性
HttpMethod请求方式,覆盖注解的 method 属性
@RequestHeader添加到请求中 header。参数类型可以为 Map<String,?>, MultiValueMap<String,?>,单个值或者 Collection<?>
@PathVariableurl 中的占位符,参数可为单个值或 Map<String,?>
@RequestBody请求体,参数是对象
@RequestParam请求参数,单个值或 Map<String,?>, MultiValueMap<String,?>,Collection<?>
@RequestPart发送文件时使用
@CookieValue向请求中添加 cookie

接口中方法返回值

返回值类型说明
void执行请求,无需解析应答
HttpHeaders存储 response 应答的 header 信息
对象解析应答结果,转为声明的类型对象
ResponseEntity<\Void>,ResponseEntity<\T>解析应答内容,得到 ResponseEntity,从 ResponseEntity 可以获取 http 应答码,header,body 内容。

反应式的相关的返回值包含

  • Mono<Void>,
  • Mono<HttpHeaders>,
  • Mono<T>,
  • Flux<T> Mono<ResponseEntity<Void>>,
  • Mono<ResponseEntity<T>>,
  • Mono<ResponseEntity<Flux<T>>

1.3 组合使用注解  

@HttpExchange , @GetExchange 等可以组合使用。
这次使用 Albums 远程服务接口,查询 Albums 信息

step1:创建 Albums 数据类

public class Albums {
 
  private int userId;
  private int id;
  private String title;
  // ...
}

step2:创建 AlbumsService 接口

接口声明方法,提供 HTTP 远程服务。在类级别应用@HttpExchange 接口,在方法级别使用@HttpExchange , @GetExchange 等

@HttpExchange(url = "https://jsonplaceholder.typicode.com/")
public interface AlbumsService {
 
  @GetExchange("/albums/{aid}")
  Albums getById(@PathVariable Integer aid);
 
  @HttpExchange(url = "/albums/{aid}",method =  "GET", contentType = MediaType.APPLICATION_JSON_VALUE)
  Albums getByIdV2(@PathVariable Integer aid);
 
}

类级别的 url 和方法级别的 url 组合在一起为最后的请求 url 地址。

step3:声明代理

@Configuration(proxyBeanMethods = true)
public class HttpServiceConfiguration {
 
  @Bean
  public AlbumsService albumsService(){
    WebClient webClient = WebClient.create();
	HttpServiceProxyFactory proxyFactory =
		HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient))
										.build();
    return proxyFactory.createClient(AlbumsService.class);
  }
}

step4:单元测试

@SpringBootTest
public class TestHttpExchange {
 
  @Resource
  AlbumsService albumsService;
 
  @Test
  void getQuery() {
    Albums albums = albumsService.getById(1);
    System.out.println("albums = " + albums);
  }
 
  @Test
  void getQueryV2() {
    Albums albums = albumsService.getByIdV2(2);
    System.out.println("albums = " + albums);
  }
}

1.4 Java Record

测试 Java Record 作为返回类型,由框架的 HTTP 代理转换应该内容为 Record 对象

step1:创建 Albums 的 Java Record

public record AlbumsRecord(int userId, int id, String title) { }

step2:AlbumsService 接口增加新的远程访问方法,方法返回类型为 Record

@GetExchange("/albums/{aid}")
AlbumsRecord getByIdRecord(@PathVariable Integer aid);

step3:单元测试,Record 接收结果

@Test
void getQueryV3() {
   AlbumsRecord albums = albumsService.getByIdRecord(1);
   System.out.println("albums = " + albums);
}

JavaRecord 能够正确接收应该结果,转为 AlbumsRecord 对象。

1.5 定制 HTTP 请求服务  

设置 HTTP 远程的超时时间,异常处理
在创建接口代理对象前,先设置 WebClient 的有关配置。

step1:设置超时,异常处理

@Bean
public AlbumsService albumsService(){
 
	HttpClient httpClient = HttpClient.create()
			.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)  //连接超时
			.doOnConnected(conn -> {
			  conn.addHandlerLast(new ReadTimeoutHandler(10)); //读超时
			  conn.addHandlerLast(new WriteTimeoutHandler(10)); //写超时
			});
 
	WebClient webClient = WebClient.builder()
			.clientConnector(new ReactorClientHttpConnector(httpClient))
			  //定制4XX,5XX的回调函数
			.defaultStatusHandler(HttpStatusCode::isError,clientResponse -> {
				  System.out.println("******WebClient请求异常********");
				  return
					Mono.error(new RuntimeException(
					"请求异常"+ clientResponse.statusCode().value()));
				}).build();
 
 
	HttpServiceProxyFactory proxyFactory = HttpServiceProxyFactory.builder(
		WebClientAdapter.forClient(webClient)).build();
 
	return proxyFactory.createClient(AlbumsService.class);
}

step2:单元测试超时和 400 异常

  @Test
  void testError() {
    Albums albums = albumsService.getById(111);
    System.out.println("albums = " + albums);
  }

测试方法执行会触发异常代码。