NIO

表设计:一个模块 设计的表规范可以使用 id  模块id version  updateTime user 在加一个ext(存放数据 json串) 数据库很多,不方便增加字段的

buffer的使用 读进来(将数据读到buffer中),写出去(buffer中数据写出去)都是以buffer做参照物 

 

/***
*
* Buffer的作用: 1.从Buffer中读数据
* 2.写入数据到Buffer中
* 3.调用flip()方法 切换模式,写切换成读模式
* 4.调用clear()或者compact()//清楚buffer中的数据,clear清除所有的数据,compact清除读过的数据,新的数据会写在未读的数据后面
* limit即是buffer不能去读或者写的位置
* buf.flip(),将position设置为0,等于从新读写
*/
public class BufferTest {

@Test
public void testFourMethod() throws Exception{
ByteBuffer buf = ByteBuffer.allocate(1000);

CharBuffer buf1 = CharBuffer.allocate(10);//10个字符

 

File file = new File("1.txt");
FileInputStream fis = new FileInputStream(file);
FileChannel channel = fis.getChannel();
channel.read(buf);//返回-1,文件为空
buf.put((byte)'a');
buf.flip();
FileOutputStream fos = new FileOutputStream("2.txt");
FileChannel channel2 = fos.getChannel();
channel2.write(buf);

 

System.out.println("buf的容量:"+buf.capacity());
System.out.println("buf的指针:"+buf.position());
System.out.println("buf的limit:"+buf.limit());
System.out.println("buf的mark:"+buf.mark());
// buf的容量:12
// buf的指针:0
// buf的limit:12
// buf的mark:java.nio.HeapByteBuffer[pos=0 lim=12 cap=12] 
}
}

 

 

Channel 通道

1.FileChannel

2.SocketChannel

3.ServerSocketChannel

4.DatagramChannel

 

Scatter(分散) 和 Gather(聚集)

将channel中的数据读到多个buffer中

将多个buffer中的数据写到一个channel中

 

 

selector(选择器)

能够检测多个channel

Selector selector = Selector.open();//创建一个selector
//通道和selector配合使用,需要向选择器注册通道
ServerSocketChannel channel3 = new ServerSocket(9898).getChannel();

//channel与selector一起使用时,需要设置非阻塞
channel3.configureBlocking(false);
SelectionKey key = channel3.register(selector, SelectionKey.OP_READ);//该方法返回一个SelectionKey对象,

FileChannel不能切换非阻塞

SelectionKey的属性

SelectionKey.OP_CONNECT

SelectionKey.OP_ACCEPT

SelectionKey.OP_READ

SelectionKey.OP_WRITE

注册通道时可以绑定多个事件 

 

 

 

 

 

 

 

 

posted on 2018-12-28 16:25  HelloWorld20180327  阅读(98)  评论(0编辑  收藏  举报

导航