IO流模块:经常看、经常用、经常忘;
在IO流的网络模型中,以常见的「客户端-服务端」交互场景为例;

客户端与服务端进行通信「交互」,可能是同步或者异步,服务端进行「流」处理时,可能是阻塞或者非阻塞模式,当然也有自定义的业务流程需要执行,从处理逻辑看就是「读取数据-业务执行-应答写数据」的形式;
Java提供「三种」IO网络编程模型,即:「BIO同步阻塞」、「NIO同步非阻塞」、「AIO异步非阻塞」;
BIO即同步阻塞,服务端收到客户端的请求时,会启动一个线程处理,「交互」会阻塞直到整个流程结束;

这种模式如果在高并发且流程复杂耗时的场景下,客户端的请求响应会存在严重的性能问题,并且占用过多资源;
【服务端】启动ServerSocket接收客户端的请求,经过一系列逻辑之后,向客户端发送消息,注意这里线程的10秒休眠;
public class SocketServer01 {
public static void main(String[] args) throws Exception {
// 1、创建Socket服务端
ServerSocket serverSocket = new ServerSocket(8080);
// 2、方法阻塞等待,直到有客户端连接
Socket socket = serverSocket.accept();
// 3、输入流,输出流
InputStream inStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
// 4、数据接收和响应
int readLen = 0;
byte[] buf = new byte[1024];
if ((readLen=inStream.read(buf)) != -1){
// 接收数据
String readVar = new String(buf, 0, readLen) ;
System.out.println("readVar======="+readVar);
}
// 响应数据
Thread.sleep(10000);
outStream.write("sever-8080-write;".getBytes());
// 5、资源关闭
IoClose.ioClose(outStream,inStream,socket,serverSocket);
}
}
【客户端】Socket连接,先向ServerSocket发送请求,再接收其响应,由于Server端模拟耗时,Client处于长时间阻塞状态;
public class SocketClient01 {
public static void main(String[] args) throws Exception {
// 1、创建Socket客户端
Socket socket = new Socket(InetAddress.getLocalHost(), 8080);
// 2、输入流,输出流
OutputStream outStream = socket.getOutputStream();
InputStream inStream = socket.getInputStream();
// 3、数据发送和响应接收
// 发送数据
outStream.write("client-hello".getBytes());
// 接收数据
int readLen = 0;
byte[] buf = new byte[1024];
if ((readLen=inStream.read(buf)) != -1){
String readVar = new String(buf, 0, readLen) ;
System.out.println("readVar======="+readVar);
}
// 4、资源关闭
IoClose.ioClose(inStream,outStream,socket);
}
}
NIO即同步非阻塞,服务端可以实现一个线程,处理多个客户端请求连接,服务端的并发能力得到极大的提升;

这种模式下客户端的请求连接都会注册到Selector多路复用器上,多路复用器会进行轮询,对请求连接的IO流进行处理;
【服务端】单线程可以处理多个客户端请求,通过轮询多路复用器查看是否有IO请求;
public class SocketServer01 {
public static void main(String[] args) throws Exception {
try {
//启动服务开启监听
ServerSocketChannel socketChannel = ServerSocketChannel.open();
socketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8989));
// 设置非阻塞,接受客户端
socketChannel.configureBlocking(false);
// 打开多路复用器
Selector selector = Selector.open();
// 服务端Socket注册到多路复用器,指定兴趣事件
socketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 多路复用器轮询
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
while (selector.select() > 0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> selectionKeyIter = selectionKeys.iterator();
while (selectionKeyIter.hasNext()){
SelectionKey selectionKey = selectionKeyIter.next() ;
selectionKeyIter.remove();
if(selectionKey.isAcceptable()) {
// 接受新的连接
SocketChannel client = socketChannel.accept();
// 设置读非阻塞
client.configureBlocking(false);
// 注册到多路复用器
client.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
// 通道可读
SocketChannel client = (SocketChannel) selectionKey.channel();
int len = client.read(buffer);
if (len > 0){
buffer.flip();
byte[] readArr = new byte[buffer.limit()];
buffer.get(readArr);
System.out.println(client.socket().getPort() + "端口数据:" + new String(readArr));
buffer.clear();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
【客户端】每隔3秒持续的向通道内写数据,服务端通过轮询多路复用器,持续的读取数据;
public class SocketClient01 {
public static void main(String[] args) throws Exception {
try {
// 连接服务端
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8989));
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
String conVar = "client-hello";
writeBuffer.put(conVar.getBytes());
writeBuffer.flip();
// 每隔3S发送一次数据
while (true) {
Thread.sleep(3000);
writeBuffer.rewind();
socketChannel.write(writeBuffer);
writeBuffer.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
AIO即异步非阻塞,对于通道内数据的「读」和「写」动作,都是采用异步的模式,对于性能的提升是巨大的;

这与常规的第三方对接模式很相似,本地服务在请求第三方服务时,请求过程耗时很大,会异步执行,第三方第一次回调,确认请求可以被执行;第二次回调则是推送处理结果,这种思想在处理复杂问题时,可以很大程度的提高性能,节省资源:
【服务端】各种「accept」、「read」、「write」动作是异步,通过Future来获取计算的结果;
public class SocketServer01 {
public static void main(String[] args) throws Exception {
// 启动服务开启监听
AsynchronousServerSocketChannel socketChannel = AsynchronousServerSocketChannel.open() ;
socketChannel.bind(new InetSocketAddress("127.0.0.1", 8989));
// 指定30秒内获取客户端连接,否则超时
Future<AsynchronousSocketChannel> acceptFuture = socketChannel.accept();
AsynchronousSocketChannel asyChannel = acceptFuture.get(30, TimeUnit.SECONDS);
if (asyChannel != null && asyChannel.isOpen()){
// 读数据
ByteBuffer inBuffer = ByteBuffer.allocate(1024);
Future<Integer> readResult = asyChannel.read(inBuffer);
readResult.get();
System.out.println("read:"+new String(inBuffer.array()));
// 写数据
inBuffer.flip();
Future<Integer> writeResult = asyChannel.write(ByteBuffer.wrap("server-hello".getBytes()));
writeResult.get();
}
// 关闭资源
asyChannel.close();
}
}
【客户端】相关「connect」、「read」、「write」方法调用是异步的,通过Future来获取计算的结果;
public class SocketClient01 {
public static void main(String[] args) throws Exception {
// 连接服务端
AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
Future<Void> result = socketChannel.connect(new InetSocketAddress("127.0.0.1", 8989));
result.get();
// 写数据
String conVar = "client-hello";
ByteBuffer reqBuffer = ByteBuffer.wrap(conVar.getBytes());
Future<Integer> writeFuture = socketChannel.write(reqBuffer);
writeFuture.get();
// 读数据
ByteBuffer inBuffer = ByteBuffer.allocate(1024);
Future<Integer> readFuture = socketChannel.read(inBuffer);
readFuture.get();
System.out.println("read:"+new String(inBuffer.array()));
// 关闭资源
socketChannel.close();
}
}
这部分内容,可以参考「Doug Lea的《IO》」文档,查看更多细节;
Reactor模式基于事件驱动设计,也称为「反应器」模式或者「分发者」模式;服务端收到多个客户端请求后,会将请求分派给对应的线程处理;

Reactor:负责事件的监听和分发;Handler:负责处理事件,核心逻辑「read读」、「decode解码」、「compute业务计算」、「encode编码」、「send应答数据」;

【1】Reactor线程通过select监听客户端的请求事件,收到事件后通过Dispatch进行分发;
【2】如果是建立连接请求事件,Acceptor通过「accept」方法获取连接,并创建一个Handler对象来处理后续业务;
【3】如果不是连接请求事件,则Reactor会将该事件交由当前连接的Handler来处理;
【4】在Handler中,会完成相应的业务流程;
这种模式将所有逻辑「连接、读写、业务」放在一个线程中处理,避免多线程的通信,资源竞争等问题,但是存在明显的并发和性能问题;

【1】Reactor线程通过select监听客户端的请求事件,收到事件后通过Dispatch进行分发;
【2】如果是建立连接请求事件,Acceptor通过「accept」方法获取连接,并创建一个Handler对象来处理后续业务;
【3】如果不是连接请求事件,则Reactor会将该事件交由当前连接的Handler来处理;
【4】在Handler中,只负责事件响应不处理具体业务,将数据发送给Worker线程池来处理;
【5】Worker线程池会分配具体的线程来处理业务,最后把结果返回给Handler做响应;
这种模式将业务从Reactor单线程分离处理,可以让其更专注于事件的分发和调度,Handler使用多线程也充分的利用cpu的处理能力,导致逻辑变的更加复杂,Reactor单线程依旧存在高并发的性能问题;

【1】 MainReactor主线程通过select监听客户端的请求事件,收到事件后通过Dispatch进行分发;
【2】如果是建立连接请求事件,Acceptor通过「accept」方法获取连接,之后MainReactor将连接分配给SubReactor;
【3】如果不是连接请求事件,则MainReactor将连接分配给SubReactor,SubReactor调用当前连接的Handler来处理;
【4】在Handler中,只负责事件响应不处理具体业务,将数据发送给Worker线程池来处理;
【5】Worker线程池会分配具体的线程来处理业务,最后把结果返回给Handler做响应;
这种模式Reactor线程分工明确,MainReactor负责接收新的请求连接,SubReactor负责后续的交互业务,适应于高并发的处理场景,是Netty组件通信框架的所采用的模式;
【服务端】提供两个EventLoopGroup,「ParentGroup」主要是用来接收客户端的请求连接,真正的处理是转交给「ChildGroup」执行,即Reactor多线程模型;
@Slf4j
public class NettyServer {
public static void main(String[] args) {
// EventLoop组,处理事件和IO
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
// 服务端启动引导类
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class).childHandler(new ServerChannelInit());
// 异步IO的结果
ChannelFuture channelFuture = serverBootstrap.bind(8989).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e){
e.printStackTrace();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
}
class ServerChannelInit extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) {
// 获取管道
ChannelPipeline pipeline = socketChannel.pipeline();
// 编码、解码器
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
// 添加自定义的handler
pipeline.addLast("serverHandler", new ServerHandler());
}
}
class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* 通道读和写
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server-Msg【"+msg+"】");
TimeUnit.MILLISECONDS.sleep(2000);
String nowTime = DateTime.now().toString(DatePattern.NORM_DATETIME_PATTERN) ;
ctx.channel().writeAndFlush("hello-client;time:" + nowTime);
ctx.fireChannelActive();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
【客户端】通过Bootstrap类,与服务器建立连接,服务端通过ServerBootstrap启动服务,绑定在8989端口,然后服务端和客户端进行通信;
public class NettyClient {
public static void main(String[] args) {
// EventLoop处理事件和IO
NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
// 客户端通道引导
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class).handler(new ClientChannelInit());
// 异步IO的结果
ChannelFuture channelFuture = bootstrap.connect("localhost", 8989).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e){
e.printStackTrace();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
class ClientChannelInit extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) {
// 获取管道
ChannelPipeline pipeline = socketChannel.pipeline();
// 编码、解码器
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
// 添加自定义的handler
pipeline.addLast("clientHandler", new ClientHandler());
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
/**
* 通道读和写
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Client-Msg【"+msg+"】");
TimeUnit.MILLISECONDS.sleep(2000);
String nowTime = DateTime.now().toString(DatePattern.NORM_DATETIME_PATTERN) ;
ctx.channel().writeAndFlush("hello-server;time:" + nowTime);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.channel().writeAndFlush("channel...active");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
编程文档:
https://gitee.com/cicadasmile/butte-java-note
应用仓库:
https://gitee.com/cicadasmile/butte-flyer-parent
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs
我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下