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

动力节点SpringBoot3第六章

6 远程访问@HttpExchange[SpringBoot 3]

远程访问是开发的常用技术,一个应用能够访问其他应用的功能。Spring Boot提供了多种远程访问的技术。 基于HTTP协议的远程访问是支付最广泛的。Spring Boot3提供了新的HTTP的访问能力,通过接口简化HTTP远程访问,类似Feign功能。Spring包装了底层HTTP客户的访问细节。 SpringBoot中定义接口提供HTTP服务。生成的代理对象实现此接口,代理对象实现HTTP的远程访问。需要理解:

[if !supportLists]· [endif]@HttpExchange 

[if !supportLists]· [endif]WebClient

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

[if !supportLists]· [endif]非阻塞,异步请求

[if !supportLists]· [endif]它的响应式编程的基于Reactor

[if !supportLists]· [endif]高并发,硬件资源少。

[if !supportLists]· [endif]支持Java 8 lambdas 函数式编程

什么是异步非阻塞理解:异步和同步,非阻塞和阻塞上面都是针对对象不一样异步和同步针对调度者,调用者发送请求,如果等待对方回应之后才去做其他事情,就是同步,如果发送请求之后不等着对方回应就去做其他事情就是异步

阻塞和非阻塞针对被调度者,被调度者收到请求后,做完请求任务之后才给出反馈就是阻塞,收到请求之后马上给出反馈然后去做事情,就是非阻塞

6.1 准备工作:

1.安装GsonFormat插件,方便json和Bean的转换 2.介绍一个免费的、24h在线的Rest Http服务,每月提供近20亿的请求,关键还是免费的、可公开访问的。https://jsonplaceholder.typicode.com/

6.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依赖。包名称:com.bjpowernode.http

step1:Maven依赖pom.xml

|  org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-webflux

step2:声明Todo数据类

| /**

[if !supportLists]· [endif]根据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(@RequestBodyTodo newTodo);  @PutExchange("/todos/{id}") ResponseEntity 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 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.1 Http服务接口的方法定义

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

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

[if !supportLists]· [endif]GetExchange

[if !supportLists]· [endif]PostExchange

[if !supportLists]· [endif]PutExchange

[if !supportLists]· [endif]PatchExchange

[if !supportLists]· [endif]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, MultiValueMap,单个值 或者 Collection

@PathVariable url中的占位符,参数可为单个值或Map<String,?>

@RequestBody 请求体,参数是对象

@RequestParam 请求参数,单个值或Map, MultiValueMap,Collection

@RequestPart 发送文件时使用

@CookieValue 向请求中添加cookie

接口中方法返回值

返回值类型说明

void执行请求,无需解析应答

HttpHeaders存储response应答的header信息

对象解析应答结果,转为声明的类型对象

ResponseEntity,ResponseEntity解析应答内容,得到ResponseEntity,从ResponseEntity可以获取http应答码,header,body内容。

反应式的相关的返回值包含Mono,Mono,Mono,Flux Mono,Mono,Mono。

6.1.1.2 组合使用注解

@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.3 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.4 定制HTTP请求服务

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

step1:设置超时,异常处理

@Beanpublic 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);

}

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,699评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,124评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,127评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,342评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,356评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,057评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,654评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,572评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,095评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,205评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,343评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,015评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,704评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,196评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,320评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,690评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,348评论 2 358

推荐阅读更多精彩内容