netty中Future和ChannelHandler

netty中的Future,繼承自 jdk中的Future,, jdk中的Future,很垃圾,只能同步阻塞獲取結果,,,

netty中的Future進行了升級,,可以addListener()異步獲取結果,,可以isSuccess()判斷任務成功還是失敗,,

  • jdk的Future
    • get()
    • isDone()
    • cancel() : 取消當前任務
  public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService service = Executors.newFixedThreadPool(2);Future<Integer> future = service.submit(() -> {log.debug("running...");Thread.sleep(2000);return 2;});Integer i = future.get();log.debug("i = " + i);}
  • netty中的Future
    • isSuccess() : 判斷任務是否成功
    • sync() : 同步等待,,任務不成功會拋錯
    • getNow() : 獲取結果,沒有就返回null
    • await() : 同步等待,,任務不成功不會報錯,,后面通過isSuccess()判斷是否成功
    • addListener() : 任務結束回調
  public static void main(String[] args) {// netty中的線程池  eventLoop,, eventloop中就一個線程NioEventLoopGroup group = new NioEventLoopGroup(2);EventLoop eventLoop = group.next();Future<String> future = eventLoop.submit(() -> {Thread.sleep(2000);return "hehe";});String now = future.getNow();System.out.println("now = " + now);boolean success = future.isSuccess();System.out.println("success = " + success);future.addListener(new GenericFutureListener<Future<? super String>>() {@Overridepublic void operationComplete(Future<? super String> future) throws Exception {Object now1 = future.getNow();System.out.println("now1 = " + now1);boolean success = future.isSuccess();System.out.println("success = " + success);}});}
  • netty中的Promise
    繼承自netty的Future,
    Promise可以設置成功和失敗,,不用等到任務結束
    public static void main(String[] args) throws ExecutionException, InterruptedException {EventLoopGroup group = new NioEventLoopGroup(2);EventLoop eventLoop = group.next();// 主動創建promise  ===> 結果的容器,DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);new Thread(()->{System.out.println("開始計算");try {int i = 1/0;Thread.sleep(1000);promise.setSuccess(1000);} catch (InterruptedException e) {e.printStackTrace();promise.setFailure(e);}//}).start();Integer i = promise.get();System.out.println("i = " + i);}
ChannelHandler

netty中handler分為兩類:

  • ChannelInboundHandler : 入站,, 讀取數據,,,channel按照添加順序依次執行
  • ChannelOutboundHandler :出站 : 發送數據,,channel 逆序執行

channel.wirte() : 從末尾逆序執行
ctx.wirte() : 是從當前的handler,往前面找ChannelOutboundHandler執行

 public static void main(String[] args) {new ServerBootstrap().group(new NioEventLoopGroup(2)).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// 添加處理器  ,,, netty會自動添加兩個handler,,一個叫head,,一個叫tail,,,// 底層是 雙向鏈表pipeline.addLast("handle01",new ChannelInboundHandlerAdapter(){// 入站的handler,,一般關心的 read@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {log.debug("msg:{}",msg);ByteBuf byteBuf = (ByteBuf) msg;String s = byteBuf.toString(Charset.defaultCharset());// 調用下一個handle       ctx.fireChannelRead(msg);,,并且將處理完成的結果,傳遞給下一個handlersuper.channelRead(ctx, s);}});pipeline.addLast("handle02",new ChannelInboundHandlerAdapter(){// 入站的handler,,一般關心的 read@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {log.debug("msg222:{}",msg);User user = new User();user.setName(((String) msg));super.channelRead(ctx, user);}});pipeline.addLast("handle03",new ChannelInboundHandlerAdapter(){// 入站的handler,,一般關心的 read@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {log.debug("msg333:{}",msg);super.channelRead(ctx, msg);ch.writeAndFlush(ctx.alloc().buffer().writeBytes("server".getBytes()));}});// 出站是,,從后面往前走  ,,只有有寫出的時候,才會觸發出站方法,,,,pipeline.addLast("handle04",new ChannelOutboundHandlerAdapter(){@Overridepublic void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {log.debug("msg444:{}",msg);super.write(ctx, msg, promise);}});pipeline.addLast("handle05",new ChannelOutboundHandlerAdapter(){@Overridepublic void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {log.debug("msg555:{}",msg);super.write(ctx, msg, promise);}});}}).bind(new InetSocketAddress(8080));}
EmbeddedChannel 模擬channel執行
    public static void main(String[] args) {ChannelInboundHandlerAdapter h1 = new ChannelInboundHandlerAdapter(){@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("msg = " + msg);super.channelRead(ctx, msg);}};ChannelOutboundHandlerAdapter h2 = new ChannelOutboundHandlerAdapter(){@Overridepublic void write(ChannelHandlerContext channelHandlerContext, Object o, ChannelPromise channelPromise) throws Exception {System.out.println(4444);}};EmbeddedChannel channel = new EmbeddedChannel(h1,h2);
//        channel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hehe".getBytes()));channel.writeOutbound(channel.writeOutbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hehe".getBytes())));}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/72587.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/72587.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/72587.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java 初學知識點總結

自己總結著玩 1.基本框架 public class HelloWorld{ public static void main(String[] args){ }//類名用大寫字母開頭 } 2.輸入&#xff1a; (1)Scanner:可讀取各種類型&#xff0c;字符串相當于cin>>; Scanner anew Scanner(System.in); Scan…

質量屬性場景描述

為了精確描述軟件系統的質量屬性&#xff0c;通常采用質量屬性場景&#xff08;Quality Attribute Scenario&#xff09;作為描述質量屬性的手段。質量屬性場景是一個具體的質量屬性需求&#xff0c;使利益相關者與系統的交互的簡短陳述。 質量屬性場景是一種用于描述系統如何…

數據可攜帶權的多重價值與實踐思考

文章目錄 前言一、數據可攜帶權的提出與立法二、數據可攜帶權的多重價值1、推動數據要素市場化配置2、促進市場競爭與創新3、強化個人數據權益 三、數據可攜帶權的實踐挑戰1、數據安全與隱私保護面臨風險2、接口差異導致數據遷移成本高昂3、可攜帶的數據范圍尚存爭議 數據可攜帶…

藍橋每日打卡--分考場

#藍橋#JAVA#分考場 題目描述 n個人參加某項特殊考試。 為了公平&#xff0c;要求任何兩個認識的人不能分在同一個考場。 求是少需要分幾個考場才能滿足條件。 輸入描述 輸入格式&#xff1a; 第一行&#xff0c;一個整數n(1≤n≤100)&#xff0c;表示參加考試的人數。 …

RMAN備份bug-審計日志暴漲(select action from gv$session)

問題概述 /oracle 文件系統使用率過大&#xff0c;經過檢查是審計日志過大,/oracle 目錄 197G 審計日志占用70G&#xff0c;每6個小時產生大量審計日志&#xff0c;日志內容全是select action from gv$session &#xff0c;猜測可能跟備份有關&#xff0c; $>df -h /oracle…

在Blender中給SP分紋理組

在Blender中怎么分SP的紋理組/紋理集 其實紋理組就是材質 把同一組的材質分給同一組的模型 導入到sp里面自然就是同一個紋理組 把模型導入SP之后 就自動分好了

Nuxt:Nuxt3框架中onBeforeMount函數 和onBeforeRouteUpdate函數區別介紹 【超詳細!】

提示&#xff1a;在 Nuxt3 中&#xff0c;onBeforeMount 和 onBeforeRouteUpdate 是兩個不同場景下使用的鉤子函數&#xff0c;分別對應 Vue 組件生命周期 和 路由導航守衛。以下是它們的詳細解釋和對比&#xff1a; 文章目錄 一、onBeforeMount&#xff08;Vue 生命周期鉤子&a…

華為 Open Gauss 數據庫在 Spring Boot 中使用 Flyway

db-migration&#xff1a;Flyway、Liquibase 擴展支持達夢&#xff08;DM&#xff09;、南大通用&#xff08;GBase 8s&#xff09;、OpenGauss 等國產數據庫。部分數據庫直接支持 Flowable 工作流。 開源代碼倉庫 Github&#xff1a;https://github.com/mengweijin/db-migrat…

java 查找兩個集合的交集部分數據

利用了Java 8的Stream API&#xff0c;代碼簡潔且效率高 import java.util.stream.Collectors; import java.util.List; import java.util.HashSet; import java.util.Set;public class ListIntersection {public static List<Long> findIntersection(List<Long> …

雙足機器狗開發:Rider - Pi

雙足機器狗開發:Rider - Pi https://github.com/YahboomTechnology/Rider-Pi-Robot 項目介紹 Rider - Pi是一款為開發者、教育工作者和機器人愛好者設計的桌面雙輪腿式機器人,它基于樹莓派CM4核心模塊構建,具備多種先進功能和特點: 硬件特性 核心模塊:采用樹莓派CM4核…

Android12 添加開機鈴聲

系統默認是沒有播放開機鈴聲的功能&#xff0c;MTK有一套自己的開機鈴聲處理邏輯&#xff0c;代碼在/vendor/mediatek/proprietary/operator/frameworks/bootanimation/MtkBootanimation下&#xff0c;但是在10之后MTK就不在維護這部分代碼了。直接使用會有很多編譯報錯&#x…

3.6V-30V寬壓輸入降壓同步IC內置MOS,電流4A/5A/6A,可以滿足汽車應急電源,BMS電池,電池組USB口輸出等儲能應用

今天給大家介紹一下這三款產品&#xff0c;分別是CJ92340,輸入電壓4.5V-30V&#xff0c;輸出可調&#xff0c;電流負載能力可達4A&#xff0c;頻率350KHZ。CJ92350,輸入電壓3.6V-30V&#xff0c;輸出可調&#xff0c;頻率可調&#xff0c;帶載能力達5A。CJ92360,輸入電壓3.6V-3…

代碼隨想錄算法訓練營第35天 | 01背包問題二維、01背包問題一維、416. 分割等和子集

一、01背包問題二維 二維數組&#xff0c;一維為物品&#xff0c;二維為背包重量 import java.util.Scanner;public class Main{public static void main(String[] args){Scanner scanner new Scanner(System.in);int n scanner.nextInt();int bag scanner.nextInt();int[…

010---基于Verilog HDL的分頻器設計

文章目錄 摘要一、時序圖二、程序設計2.1 rtl2.2 tb 三、仿真分析四、實用性 摘要 文章為學習記錄。繪制時序圖&#xff0c;編碼。通過修改分頻值參數&#xff0c;實現一定范圍分頻值內的任意分頻器設計。 一、時序圖 二、程序設計 2.1 rtl module divider #(parameter D…

維度建模事實表技術基礎解析(以電商場景為例)

維度建模事實表技術基礎解析(以電商場景為例) 1. 事實表結構 定義:事實表是維度建模的核心,由外鍵(關聯維度表)、度量值(可量化的業務指標)及退化維度(冗余的維度屬性)組成。其本質是記錄業務過程中的度量事件,例如電商訂單金額、商品庫存量等。 場景識別:適用于…

Redis 主從復制、哨兵與集群的關系及工作原理詳解

一、核心概念與關系 Redis 的 主從復制、哨兵&#xff08;Sentinel&#xff09; 和 集群&#xff08;Cluster&#xff09; 是逐步演進的高可用與分布式解決方案&#xff0c;三者關系如下&#xff1a; 主從復制&#xff1a;數據冗余與讀寫分離的基礎。 哨兵&#xff1a;在主從…

確認機制的分類及其區別與聯系探討

在傳輸控制中&#xff0c;確認機制&#xff08;ACK 機制&#xff09;作為反饋模塊在實現擁塞控制、丟包恢復和狀態監測等功能中起到了至關重要的作用。今天我將基于之前發表的論文研究成果&#xff0c;對確認機制的分類進行系統梳理&#xff0c;并討論各類機制之間的區別與聯系…

115 道 MySQL 面試題,從簡單到深入!

1. 什么是數據庫事務&#xff1f; 數據庫事務是一個作為單個邏輯工作單元執行的一系列操作。事務具有ACID屬性&#xff0c;即原子性&#xff08;Atomicity&#xff09;、一致性&#xff08;Consistency&#xff09;、隔離性&#xff08;Isolation&#xff09;和持久性&#xf…

Linux - 網絡套接字

一、網絡編程 1&#xff09;地址結構 1. IP地址結構 struct in_addr&#xff1a;是用于表示 IPv4 地址 的結構體&#xff0c;定義在頭文件 <netinet/in.h> 中。它的主要作用是存儲一個 32 位的 IPv4 地址&#xff0c;通常與 struct sockaddr_in 一起使用。 struct in_a…

程序員學商務英語之Visiting the Factory

Dialogue-1 Arranging a Visit安排參觀 I was wondering if you would / could lend me a million bucks, you know, I’m trying to start / run my own business. 我想知道你是否能夠借給我一百萬美金&#xff0c;你知道&#xff0c;我正在創業。 Take off your tie befor…