Netty In Action中文版,nettyaction

來源:互聯網
上載者:User

Netty In Action中文版,nettyaction

http://blog.csdn.net/abc_key/article/details/38388031

        本章講述Netty中如何輕鬆實現定製的轉碼器,由於Netty架構的靈活性,這些轉碼器易於重用和測試。為了更容易實現,使用Memcached作為協議例子是因為它更方便我們實現。

        Memcached是免費開源、高效能、分布式的記憶體對象緩衝系統,其目的是加速動態Web應用程式的響應,減輕資料庫負載;Memcache實際上是一個以key-value儲存任意資料的記憶體小塊。可能有人會問“為什麼使用Memcached?”,因為Memcached協議非常簡單,便於講解。

14.1 轉碼器的範圍
        我們將只實現Memcached協議的一個子集,這足夠我們進行添加、檢索、刪除對象;在Memcached中是通過執行SET,GET,DELETE命令來實現的。Memcached支援很多其他的命令,但我們只使用其中三個命令,簡單的東西,我們才會理解的更清楚。        Memcached有一個二進位和純文字協議,它們都可以用來與Memcached伺服器通訊,使用什麼類型的協議取決於伺服器支援哪些協議。本章主要關注實現二進位協議,因為二進位在網路編程中最常用。14.2 實現Memcached的轉碼器
        當想要實現一個給定協議的轉碼器,我們應該花一些事件來瞭解它的運作原理。通常情況下,協議本身都有一些詳細的記錄。在這裡你會發現多少細節?幸運的是Memcached的二進位協議可以很好的擴充。        在RFC中有相應的規範,並提供了Memcached二進位協議:http://code.google.com/p/memcached/wiki/BinaryProtocolRevamped。我們不會執行Memcached的所有命令,只會執行三種操作:SET,GET和DELETE。這樣做事為了讓事情變得簡單。14.3 瞭解Memcached二進位協議
        可以在http://code.google.com/p/memcached/wiki/BinaryProtocolRevamped上詳細瞭解Memcached二進位協議結構。不過這個網站如果不翻牆的話好像訪問不了。14.4 Netty編碼器和解碼器14.4.1 實現Memcached編碼器
        先定義memcached作業碼(Opcode)和響應狀態代碼(Status):
package netty.in.action.mem;/** * memcached operation codes * @author c.king * */public class Opcode {public static final byte GET = 0x00;public static final byte SET = 0x01;public static final byte DELETE = 0x04;}
package netty.in.action.mem;/** * memcached response statuses * @author c.king * */public class Status {public static final short NO_ERROR = 0x0000;public static final short KEY_NOT_FOUND = 0x0001;public static final short KEY_EXISTS = 0x0002;public static final short VALUE_TOO_LARGE = 0x0003;public static final short INVALID_ARGUMENTS = 0x0004;public static final short ITEM_NOT_STORED = 0x0005;public static final short INC_DEC_NON_NUM_VAL = 0x0006;}
        繼續編寫memcached請求訊息體:
package netty.in.action.mem;import java.util.Random;/** * memcached request message object * @author c.king * */public class MemcachedRequest {private static final Random rand = new Random();private int magic = 0x80;// fixed so hard codedprivate byte opCode; // the operation e.g. set or getprivate String key; // the key to delete, get or setprivate int flags = 0xdeadbeef; // randomprivate int expires; // 0 = item never expiresprivate String body; // if opCode is set, the valueprivate int id = rand.nextInt(); // Opaqueprivate long cas; // data version check...not usedprivate boolean hasExtras; // not all ops have extraspublic MemcachedRequest(byte opcode, String key, String value) {this.opCode = opcode;this.key = key;this.body = value == null ? "" : value;// only set command has extras in our examplehasExtras = opcode == Opcode.SET;}public MemcachedRequest(byte opCode, String key) {this(opCode, key, null);}public int getMagic() {return magic;}public byte getOpCode() {return opCode;}public String getKey() {return key;}public int getFlags() {return flags;}public int getExpires() {return expires;}public String getBody() {return body;}public int getId() {return id;}public long getCas() {return cas;}public boolean isHasExtras() {return hasExtras;}}
        最後編寫memcached請求編碼器:
package netty.in.action.mem;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.MessageToByteEncoder;import io.netty.util.CharsetUtil;/** * memcached request encoder * @author c.king * */public class MemcachedRequestEncoder extends MessageToByteEncoder<MemcachedRequest> {@Overrideprotected void encode(ChannelHandlerContext ctx, MemcachedRequest msg, ByteBuf out)throws Exception {// convert key and body to bytes arraybyte[] key = msg.getKey().getBytes(CharsetUtil.UTF_8);byte[] body = msg.getBody().getBytes(CharsetUtil.UTF_8);// total size of body = key size + body size + extras sizeint bodySize = key.length + body.length + (msg.isHasExtras() ? 8 : 0);// write magic intout.writeInt(msg.getMagic());// write opcode byteout.writeByte(msg.getOpCode());// write key length (2 byte) i.e a Java shortout.writeShort(key.length);// write extras length (1 byte)int extraSize = msg.isHasExtras() ? 0x08 : 0x0;out.writeByte(extraSize);// byte is the data type, not currently implemented in Memcached// but requiredout.writeByte(0);// next two bytes are reserved, not currently implemented// but are requiredout.writeShort(0);// write total body length ( 4 bytes - 32 bit int)out.writeInt(bodySize);// write opaque ( 4 bytes) - a 32 bit int that is returned// in the responseout.writeInt(msg.getId());// write CAS ( 8 bytes)// 24 byte header finishes with the CASout.writeLong(msg.getCas());if(msg.isHasExtras()){// write extras// (flags and expiry, 4 bytes each), 8 bytes totalout.writeInt(msg.getFlags());out.writeInt(msg.getExpires());}//write keyout.writeBytes(key);//write valueout.writeBytes(body);}}
14.4.2 實現Memcached解碼器
        編寫memcached響應訊息體:
package netty.in.action.mem;/** * memcached response message object * @author c.king * */public class MemcachedResponse {private byte magic;private byte opCode;private byte dataType;private short status;private int id;private long cas;private int flags;private int expires;private String key;private String data;public MemcachedResponse(byte magic, byte opCode, byte dataType, short status,int id, long cas, int flags, int expires, String key, String data) {this.magic = magic;this.opCode = opCode;this.dataType = dataType;this.status = status;this.id = id;this.cas = cas;this.flags = flags;this.expires = expires;this.key = key;this.data = data;}public byte getMagic() {return magic;}public byte getOpCode() {return opCode;}public byte getDataType() {return dataType;}public short getStatus() {return status;}public int getId() {return id;}public long getCas() {return cas;}public int getFlags() {return flags;}public int getExpires() {return expires;}public String getKey() {return key;}public String getData() {return data;}}
        編寫memcached響應解碼器:
package netty.in.action.mem;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.ByteToMessageDecoder;import io.netty.util.CharsetUtil;import java.util.List;public class MemcachedResponseDecoder extends ByteToMessageDecoder {private enum State {Header, Body}private State state = State.Header;private int totalBodySize;private byte magic;private byte opCode;private short keyLength;private byte extraLength;private byte dataType;private short status;private int id;private long cas;@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)throws Exception {switch (state) {case Header:// response header is 24 bytesif (in.readableBytes() < 24) {return;}// read headermagic = in.readByte();opCode = in.readByte();keyLength = in.readShort();extraLength = in.readByte();dataType = in.readByte();status = in.readShort();totalBodySize = in.readInt();id = in.readInt();cas = in.readLong();state = State.Body;break;case Body:if (in.readableBytes() < totalBodySize) {return;}int flags = 0;int expires = 0;int actualBodySize = totalBodySize;if (extraLength > 0) {flags = in.readInt();actualBodySize -= 4;}if (extraLength > 4) {expires = in.readInt();actualBodySize -= 4;}String key = "";if (keyLength > 0) {ByteBuf keyBytes = in.readBytes(keyLength);key = keyBytes.toString(CharsetUtil.UTF_8);actualBodySize -= keyLength;}ByteBuf body = in.readBytes(actualBodySize);String data = body.toString(CharsetUtil.UTF_8);out.add(new MemcachedResponse(magic, opCode, dataType, status,id, cas, flags, expires, key, data));state = State.Header;break;default:break;}}}
14.5 測試轉碼器
        基於netty的轉碼器都寫完了,下面我們來寫一個測試它的類:
package netty.in.action.mem;import io.netty.buffer.ByteBuf;import io.netty.channel.embedded.EmbeddedChannel;import io.netty.util.CharsetUtil;import org.junit.Assert;import org.junit.Test;/** * test memcached encoder * @author c.king * */public class MemcachedRequestEncoderTest {@Testpublic void testMemcachedRequestEncoder() {MemcachedRequest request = new MemcachedRequest(Opcode.SET, "k1", "v1");EmbeddedChannel channel = new EmbeddedChannel(new MemcachedRequestEncoder());Assert.assertTrue(channel.writeOutbound(request));ByteBuf encoded = (ByteBuf) channel.readOutbound();Assert.assertNotNull(encoded);Assert.assertEquals(request.getMagic(), encoded.readInt());Assert.assertEquals(request.getOpCode(), encoded.readByte());Assert.assertEquals(2, encoded.readShort());Assert.assertEquals((byte) 0x08, encoded.readByte());Assert.assertEquals((byte) 0, encoded.readByte());Assert.assertEquals(0, encoded.readShort());Assert.assertEquals(2 + 2 + 8, encoded.readInt());Assert.assertEquals(request.getId(), encoded.readInt());Assert.assertEquals(request.getCas(), encoded.readLong());Assert.assertEquals(request.getFlags(), encoded.readInt());Assert.assertEquals(request.getExpires(), encoded.readInt());byte[] data = new byte[encoded.readableBytes()];encoded.readBytes(data);Assert.assertArrayEquals((request.getKey() + request.getBody()).getBytes(CharsetUtil.UTF_8), data);Assert.assertFalse(encoded.isReadable());Assert.assertFalse(channel.finish());Assert.assertNull(channel.readInbound());}}
package netty.in.action.mem;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.embedded.EmbeddedChannel;import io.netty.util.CharsetUtil;import org.junit.Assert;import org.junit.Test;/** * test memcached decoder *  * @author c.king *  */public class MemcachedResponseDecoderTest {@Testpublic void testMemcachedResponseDecoder() {EmbeddedChannel channel = new EmbeddedChannel(new MemcachedResponseDecoder());byte magic = 1;byte opCode = Opcode.SET;byte dataType = 0;byte[] key = "Key1".getBytes(CharsetUtil.UTF_8);byte[] body = "Value".getBytes(CharsetUtil.UTF_8);int id = (int) System.currentTimeMillis();long cas = System.currentTimeMillis();ByteBuf buffer = Unpooled.buffer();buffer.writeByte(magic);buffer.writeByte(opCode);buffer.writeShort(key.length);buffer.writeByte(0);buffer.writeByte(dataType);buffer.writeShort(Status.KEY_EXISTS);buffer.writeInt(body.length + key.length);buffer.writeInt(id);buffer.writeLong(cas);buffer.writeBytes(key);buffer.writeBytes(body);Assert.assertTrue(channel.writeInbound(buffer));MemcachedResponse response = (MemcachedResponse) channel.readInbound();assertResponse(response, magic, opCode, dataType, Status.KEY_EXISTS, 0,0, id, cas, key, body);}private static void assertResponse(MemcachedResponse response, byte magic,byte opCode, byte dataType, short status, int expires, int flags,int id, long cas, byte[] key, byte[] body) {Assert.assertEquals(magic, response.getMagic());Assert.assertArrayEquals(key,response.getKey().getBytes(CharsetUtil.UTF_8));Assert.assertEquals(opCode, response.getOpCode());Assert.assertEquals(dataType, response.getDataType());Assert.assertEquals(status, response.getStatus());Assert.assertEquals(cas, response.getCas());Assert.assertEquals(expires, response.getExpires());Assert.assertEquals(flags, response.getFlags());Assert.assertArrayEquals(body,response.getData().getBytes(CharsetUtil.UTF_8));Assert.assertEquals(id, response.getId());}}
14.6 Summary
        本章主要是使用netty寫了個類比memcached二進位協議的處理。至於memcached二進位協議具體是個啥玩意,可以單獨瞭解,這裡也沒有詳細說明。
錯誤提示
Struts In Action與Struts In Action中文版2有什不同

Apache Struts 2即是之前大家所熟知的WebWork 2。在經曆了幾年的各自發展後,WebWork和Struts社區決定合二為一,也即是Struts 2
Action 類:
Struts1要求Action類繼承一個抽象基類。Struts1的一個普遍問題是使用抽象類別編程而不是介面。
Struts 2 Action類可以實現一個Action介面,也可實現其他介面,使可選和定製的服務成為可能。Struts2提供一個ActionSupport基類去實現 常用的介面。Action介面不是必須的,任何有execute標識的POJO對象都可以用作Struts2的Action對象。
線程模式:
Struts1 Action是單例模式並且必須是安全執行緒的,因為僅有Action的一個執行個體來處理所有的請求。單例策略限制了Struts1 Action能作的事,並且要在開發時特別小心。Action資源必須是安全執行緒的或同步的。
Struts2 Action對象為每一個請求產生一個執行個體,因此沒有安全執行緒問題。(實際上,servlet容器給每個請求產生許多可丟棄的對象,並且不會導致效能和記憶體回收問題)
Servlet 依賴:
Struts1 Action 依賴於Servlet API ,因為當一個Action被調用時HttpServletRequest 和 HttpServletResponse 被傳遞給execute方法。
Struts 2 Action不依賴於容器,允許Action脫離容器單獨被測試。如果需要,Struts2 Action仍然可以訪問初始的request和response。但是,其他的元素減少或者消除了直接存取HttpServetRequest 和 HttpServletResponse的必要性。
可測性:
測試Struts1 Action的一個主要問題是execute方法暴露了servlet API(這使得測試要依賴於容器)。一個第三方擴充--Struts TestCase--提供了一套Struts1的類比對象(來進行測試)。
Struts 2 Action可以通過初始化、設定屬性、調用方法來測試,“依賴注入”支援也使測試更容易。
捕獲輸入:
Struts1 使用ActionForm對象捕獲輸入。所有的ActionForm必須繼承一個基類。因為其他JavaBean不能用作ActionForm,開發人員經常建立多餘的類捕獲輸入。動態Bean(DynaBeans)可以作為建立傳統ActionForm的選擇,但是,開發人員可能是在重新描述(建立)已經存在的JavaBean(仍然會導致有冗餘的javabean)。
Struts 2直接使用Action屬性作為輸入屬性,消除了對第二個輸入對象的需求。輸入屬性可能是有自己(子)屬性的rich物件類型。Action屬效能夠通過web頁面上的taglibs訪問。Struts2也支援ActionForm模式。rich物件類型,包括業務對象,能夠用作輸入/輸出對象。這種ModelDriven 特性簡化了taglib對POJO輸入對象的引用。
運算式語言:
Struts1 整合了JSTL,因此使用JSTL EL。這種EL有基本對象圖遍曆,但是對集合和索引屬性的支援很弱。
Struts2可以使用JSTL,但是也支援一個更強大和靈活的運算式語言--"Object Graph Notation Language" (OGNL).
綁定值到頁面(view):
S......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.