动力节点王鹤SpringBoot3笔记——远程访问@HttpExchange[SpringBoot 3]

目录

第六章  远程访问@HttpExchange[SpringBoot 3]

6.1.1.1  准备工作: 

6.1.1.2 声明式HTTP远程服务 

6.1.1.3 Http服务接口的方法定义

6.1.1.4 组合使用注解 

6.1.1.5 Java Record

6.1.1.6  定制HTTP请求服务 


第六章  远程访问@HttpExchange[SpringBoot 3]

远程访问是开发的常用技术,一个应用能够访问其他应用的功能。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 函数式编程 

什么是异步非阻塞 

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

6.1.1.1  准备工作: 

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

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

6.1.1.2 声明式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);
  }
}

6.1.1.3 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<?>
@PathVariable url中的占位符,参数可为单个值或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<Respo nseEntity<Void>>,Mono<ResponseEntity<T>>,Mono<ResponseEntity<Flux<T>>。

6.1.1.4 组合使用注解 

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

step1:创建Albums数据类 

public class Albums {

  private int userId;
  private int id;
  private String title;

  //省略 set ,get

  @Override
  public String toString() {
    return "Albums{" +
        "userId=" + userId +
        ", id=" + id +
        ", title='" + 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);
  }
}

6.1.1.5 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对象。

6.1.1.6  定制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);
  }

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