当前位置: 代码网 > it编程>编程语言>Java > spring webClient配置及使用简单代码示例

spring webClient配置及使用简单代码示例

2024年05月18日 Java 我要评论
1.配置import com.zty.common.util.webutils;import io.netty.channel.channeloption;import io.netty.handle

1.配置

import com.zty.common.util.webutils;
import io.netty.channel.channeloption;
import io.netty.handler.timeout.readtimeouthandler;
import io.netty.handler.timeout.writetimeouthandler;
import lombok.extern.slf4j.slf4j;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.http.httpheaders;
import org.springframework.http.mediatype;
import org.springframework.http.client.reactive.reactorclienthttpconnector;
import org.springframework.web.reactive.function.client.webclient;
import reactor.netty.http.client.httpclient;
import reactor.netty.resources.connectionprovider;

import java.time.duration;

/**
 * webclient配置
 * @author zty
 */
@slf4j
@configuration
public class webclientconfig {

    @bean
    public webclient webclient(){
        //配置固定大小连接池
        connectionprovider provider = connectionprovider
                .builder("custom")
                // 等待超时时间
                .pendingacquiretimeout(duration.ofseconds(10))
                // 最大连接数
                .maxconnections(200)
                // 最大空闲时间
                .maxidletime(duration.ofseconds(5))
                // 最大等待连接数量
                .pendingacquiremaxcount(-1)
                .build();

        /**
         * doonbind	当服务器channel即将被绑定的时候调用。
         * doonbound	当服务器channel已经被绑定的时候调用。
         * doonchannelinit	当channel初始化的时候被调用。
         * doonconnection	当一个远程客户端连接上的时候被调用。
         * doonunbound	当服务器channel解绑的时候被调用。
         */
        httpclient httpclient = httpclient.create(provider)
                .option(channeloption.connect_timeout_millis, 6000)
                .option(channeloption.so_keepalive, true)
                .responsetimeout(duration.ofseconds(6))
                .keepalive(true)
                //连接成功
                .doonconnected(connection -> connection.addhandlerlast(new readtimeouthandler(6))
                        .addhandlerlast(new writetimeouthandler(6)))
                //每次请求后执行flush,防止服务器主动断开连接
                .doafterrequest((httpclientrequest, connection) -> {
                    connection.channel().alloc().buffer().release();
                    connection.channel().flush();
                    connection.channel().pipeline().flush();
                });

        return webclient.builder()
                .baseurl("http://127.0.0.1:8080")
                .defaultheader(httpheaders.content_type, mediatype.application_json_value)
                .defaultheader(httpheaders.connection, "keep-alive")
                .clientconnector(new reactorclienthttpconnector(httpclient))
                .build();
    }
}

2.使用

import com.alibaba.fastjson2.json;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.scheduling.annotation.async;
import org.springframework.stereotype.component;
import org.springframework.web.reactive.function.client.webclient;
import reactor.core.publisher.mono;

import java.util.hashmap;

/**
 * http消息发送工具
 * @author zty
 */
@slf4j
@component
public class webutils {

    @autowired
    webclient webclient;

    @async
    public void post(hashmap<string, object> message){
        // 发送请求
        webclient.post()
                // 请求路径
                .uri("/test")
                // 携带参数
                .bodyvalue(json.tojsonstring(message))
                // 获取响应体
                .retrieve()
                // 响应数据类型转换
                .bodytomono(string.class)
                .doonerror(throwable -> log.info(throwable.getmessage()))
                .onerrorresume(e -> mono.just("error " + e.getmessage()))
                // 异步
                .subscribe();
    }
}

附:一个带有多个查询参数的webclient使用示例

import org.springframework.web.reactive.function.client.webclient;

public class examplewebclient {

    public static void main(string[] args) {
        webclient client = webclient.create("https://api.example.com");

        client.get()
              .uri(uribuilder -> uribuilder.path("/search")
                                           .queryparam("q", "webclient")
                                           .queryparam("page", 1)
                                           .queryparam("size", 20)
                                           .build())
              .retrieve()
              .bodytomono(string.class)
              .subscribe(response -> system.out.println(response));
    }
}

在这个示例中,我们使用了uri()方法来构建uri。使用了一个lambda表达式,在其中的uribuilder对象(uribuilder类型)中指定了路径和查询参数。在这个例子中,我们将/search作为路径,以及三个查询参数qpagesize来进行搜索,它们的值依次为webclient(表示搜索关键字为webclient)、120

最终的uri将会是一个类似于 https://api.example.com/search?q=webclient&page=1&size=20 的字符串。在发送请求后,我们将响应体转换为string类型的mono对象,并使用subscribe()方法输出响应内容。

总结 

到此这篇关于spring webclient配置及使用的文章就介绍到这了,更多相关spring webclient配置使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com