netty 使用Java序列化
SubscribeReq
package com.zhaowb.netty.ch7_1;
import java.io.Serializable;
public class SubscribeReq implements Serializable {
private static final long serialVersionUID = 1L;
private int subReqID;
private String userName;
private String productName;
private String phoneNumber;
private String address;
public SubscribeReq() {
}
public SubscribeReq(int subReqID, String userName, String productName, String phoneNumber, String address) {
this.subReqID = subReqID;
this.userName = userName;
this.productName = productName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public int getSubReqID() {
return subReqID;
}
public void setSubReqID(int subReqID) {
this.subReqID = subReqID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "SubscribeReq{" +
"subReqID=" + subReqID +
", userName='" + userName + '\'' +
", productName='" + productName + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", address='" + address + '\'' +
'}';
}
}
SubscribeResp
package com.zhaowb.netty.ch7_1;
import java.io.Serializable;
public class SubscribeResp implements Serializable {
private static final long serialVersionUID = 1L;
private int subReqID;
private int respCode;
private String desc;
public SubscribeResp() {
}
public SubscribeResp(int subReqID, int respCode, String desc) {
this.subReqID = subReqID;
this.respCode = respCode;
this.desc = desc;
}
public int getSubReqID() {
return subReqID;
}
public void setSubReqID(int subReqID) {
this.subReqID = subReqID;
}
public int getRespCode() {
return respCode;
}
public void setRespCode(int respCode) {
this.respCode = respCode;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "SubscribeResp{" +
"subReqID=" + subReqID +
", respCode=" + respCode +
", desc='" + desc + '\'' +
'}';
}
}
SubReqServer
package com.zhaowb.netty.ch7_1; import com.zhaowb.netty.ch5_2.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; public class SubReqServer { public void bind(int port) throws Exception { // 配置 服务端的 NIO 线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception { // 创建一个 ObjectDecoder ,负责对实现 Serializable 的 POJO 对象进行解码。
// 有多个构造函数,支持不同的ClassResolver,使用weakCachingConcurrentResolver创建线程安全的
// WeakReferenceMap 对类加载器进行缓存,支持多线程并发访问,当虚拟机内存不足时,会释放缓存中
// 的内存,防止内存泄漏,为了防止异常码流和解码错误导致的内存溢出,将单个对象最大序列化后的
// 字节数组长度设置为 1M
ch.pipeline().addLast(new ObjectDecoder(1024 * 1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
// 创建 ObjectEncoder ,可以在消息发送的时候自动将实现 Serializable 的POJO 对象进行编码,
// 无需对对象手动序列化,只需要关注自己的业务逻辑处理即可,对象序列化和发序列化都由netty的对象编码解码器完成。
ch.pipeline().addLast(new ObjectEncoder());
ch.pipeline().addLast(new SubReqServerHandler());
}
}); // 绑定端口,同步等待成功。
ChannelFuture f = b.bind(port).sync();
// 等待服务端监听端口关闭。
f.channel().closeFuture().sync();
} catch (Exception e) {
// 退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
int port = 8080; if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
}
}
new SubReqServer().bind(port);
}
}
SubReqServerHandler
package com.zhaowb.netty.ch7_1; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; @ChannelHandler.Sharable
public class SubReqServerHandler extends ChannelHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
SubscribeReq req = (SubscribeReq)msg;
if( "lilinfeng".equals(req.getUserName())){ System.out.println("Server accept client subscribe req : [" + req.toString() + "]");
ctx.writeAndFlush(resp(req.getSubReqID()));
}
} public SubscribeResp resp( int subReqID){ SubscribeResp resp = new SubscribeResp();
resp.setSubReqID(subReqID);
resp.setRespCode(10);
resp.setDesc("Netty book order successd ,3 days later, sent to the designated address");
return resp;
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();// 发送异常,关闭链路
}
}
SubReqClient
package com.zhaowb.netty.ch7_1; import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder; public class SubReqClient { public void connect(int port, String host) throws Exception { //配置客户端 NIO 线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ObjectDecoder(1024*1024,ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
ch.pipeline().addLast(new ObjectEncoder());
ch.pipeline().addLast(new SubReqClientHandler());
}
});
// 发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
// 等待客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 释放 NIO 线程组
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
}
}
new SubReqClient().connect(port, "127.0.0.1");
}
}
SubReqClientHandler
package com.zhaowb.netty.ch7_1; import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class SubReqClientHandler extends ChannelHandlerAdapter { public SubReqClientHandler() {
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { for (int i=0;i<10;i++){
ctx.write(subResp(i));
}
ctx.flush();
} private SubscribeReq subResp(int i){
SubscribeReq req = new SubscribeReq();
req.setAddress("国家地质公园");
req.setPhoneNumber("5464654113");
req.setProductName("netty 权威指南");
req.setSubReqID(i);
req.setUserName("lilinfeng");
return req;
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Receive server response : [" + msg + "]");
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
netty 使用Java序列化的更多相关文章
- 编解码-java序列化
大多数Java程序员接触到的第一种序列化或者编解码技术就是Java的默认序列化,只需要序列化的POJO对象实现java.io.Serializable接口,根据实际情况生成序列ID,这个类就能够通过j ...
- (中级篇 NettyNIO编解码开发)第七章-java序列化
相信大多数Java程序员接触到的第一种序列化或者编解码技术就是.Java的默认序列化,只需要序列化的POJO对象实现java.io.Serializable接口,根据实际情况生成序列ID,这个类就能够 ...
- Netty 系列之 Netty 高性能之道 高性能的三个主题 Netty使得开发者能够轻松地接受大量打开的套接字 Java 序列化
Netty系列之Netty高性能之道 https://www.infoq.cn/article/netty-high-performance 李林锋 2014 年 5 月 29 日 话题:性能调优语言 ...
- 在Dubbo中使用高效的Java序列化(Kryo和FST)
在Dubbo中使用高效的Java序列化(Kryo和FST) 作者:沈理 文档版权:Creative Commons 3.0许可证 署名-禁止演绎 完善中…… TODO 生成可点击的目录 目录 序列化漫 ...
- Java 序列化(转)
转自 http://www.infoq.com/cn/articles/cf-java-object-serialization-rmi 对于一个存在于Java虚拟机中的对象来说,其内部的状态只保持在 ...
- 一文讲透Java序列化
本文目录 一.序列化是什么 二.为什么需要序列化 三.序列化怎么用 四.序列化深度探秘 4.1 为什么必须实现Serializable接口 4.2 被序列化对象的字段是引用时该怎么办 4.3 同一个对 ...
- Java 序列化界新贵 kryo 和熟悉的“老大哥”,就是 PowerJob 的序列化方案
本文适合有 Java 基础知识的人群 作者:HelloGitHub-Salieri HelloGitHub 推出的<讲解开源项目>系列. 项目地址: https://github.com/ ...
- Java 序列化与反序列化
1.什么是序列化?为什么要序列化? Java 序列化就是指将对象转换为字节序列的过程,而反序列化则是只将字节序列转换成目标对象的过程. 我们都知道,在进行浏览器访问的时候,我们看到的文本.图片.音频. ...
- Java序列化与反序列化
Java序列化与反序列化是什么?为什么需要序列化与反序列化?如何实现Java序列化与反序列化?本文围绕这些问题进行了探讨. 1.Java序列化与反序列化 Java序列化是指把Java对象转换为字节序列 ...
随机推荐
- 阿里云重磅推出物联网设备身份认证Link ID²
2018年12月19日,阿里云宣布推出新版物联网设备身份认证Link ID²及物联网安全运营中心Link SOC,护航万物智联. 随着越来越多的设备连接到网络中,随之而来的安全问题越来越突出. ...
- js简单图片切换
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title> ...
- NX文件名与工程图名自动关联
1.先去D:\Program Files\Siemens\NX 9.0\LOCALIZATION\prc\simpl_chinese\startup里,把默认的图框模板替换成自己定制好的模板,如何替换 ...
- 引入CSS的方法
##1 关于引入css样式的方法: 1 外部引入: <link rel="stylesheet" type="text/css" href="& ...
- LeetCode 620. Not Boring Movies (有趣的电影)
题目标签: 题目给了我们一个 cinema 表格, 让我们找出 不无聊的电影,并且id 是奇数的,降序排列. 比较直接简单的,具体看code. Java Solution: Runtime: 149 ...
- GIT学习记录3(分支管理)
学习参考地址:https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 本编随笔只是自己对 ...
- 学习笔记——CDQ分治
再次感谢这位大佬的博客:https://www.cnblogs.com/ljc20020730/p/10395866.html CDQ分治,是一种在分治合并中计算前面值对后面答案的贡献的一种算法.今天 ...
- lucene入门-搜索方式
1 package com.home.utils; import java.util.ArrayList; import java.util.List; import org.apache.lucen ...
- 初探.Net Core API 网关Ocelot(一)
一.介绍 Ocelot 是基于.NetCore实现的开源的API网关,支持IdentityServer认证.Ocelot具有路由.请求聚合.服务发现.认证.鉴权.限流熔断等功能,并内置了负载均衡器与S ...
- K8S之集群搭建
转自声明 ASP.NET Core on K8S深入学习(1)K8S基础知识与集群搭建 1.K8S环境搭建的几种方式 搭建K8S环境有几种常见的方式如下: (1)Minikube Minikube是一 ...