java开发之netty里集成spring注入mysq连接池(一)

java开发之netty里集成spring注入mysq连接池(一)
http://blog.chinaunix.net/uid-11121450-id-3147009.html

标签spring  jdbc  netty  java  注入  分类: java



 

netty的性能非常高,能达到8000rps以上,见

各个web服务器的性能对比测试

1.准备好需要的jar包


点击(此处)折叠或打开

  1. spring.jar //spring包
  2. netty-3.2.4.Final.jar // netty库
  3. commons-dbcp.jar // dbcp数据库连接池
  4. mysql-connector-java-5.1.6.jar // dbcp数据库连接池需要依赖
  5. commons-logging.jar //spring.jar需要依赖
  6. commons-pool.jar

2.新建java工程TestNettyServer

2.1导入netty的例子
HttpServer.java


点击(此处)折叠或打开

  1. package org.jboss.netty.example.http.snoop;

  2. import java.net.InetSocketAddress;
  3. import java.util.concurrent.Executors;
  4. import org.jboss.netty.bootstrap.ServerBootstrap;
  5. import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

  6. public class HttpServer {
  7.     public static void main(String[] args) {
  8.         // Configure the server.
  9.         ServerBootstrap bootstrap = new ServerBootstrap(
  10.                 new NioServerSocketChannelFactory(
  11.                         Executors.newCachedThreadPool(),
  12.                         Executors.newCachedThreadPool()));
  13.         // Set up the event pipeline factory.
  14.         bootstrap.setPipelineFactory(new HttpServerPipelineFactory());

  15.         // Bind and start to accept incoming connections.
  16.         bootstrap.bind(new InetSocketAddress(8081));
  17.     }
  18. }
HttpServerPipelineFactory.java

点击(此处)折叠或打开

  1. package org.jboss.netty.example.http.snoop;
  2.    
  3.   import static org.jboss.netty.channel.Channels.*;
  4.    
  5.   import org.jboss.netty.channel.ChannelPipeline;
  6.   import org.jboss.netty.channel.ChannelPipelineFactory;
  7.   import org.jboss.netty.handler.codec.http.HttpContentCompressor;
  8.   import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
  9.   import org.jboss.netty.handler.codec.http.HttpResponseEncoder;

  10.   public class HttpServerPipelineFactory implements ChannelPipelineFactory {
  11.       public ChannelPipeline getPipeline() throws Exception {
  12.           // Create a default pipeline implementation.
  13.           ChannelPipeline pipeline = pipeline();
  14.    
  15.           // Uncomment the following line if you want HTTPS
  16.           //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
  17.           //engine.setUseClientMode(false);
  18.           //pipeline.addLast("ssl", new SslHandler(engine));
  19.    
  20.           pipeline.addLast("decoder", new HttpRequestDecoder());
  21.           // Uncomment the following line if you don't want to handle HttpChunks.
  22.           //pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
  23.           pipeline.addLast("encoder", new HttpResponseEncoder());
  24.           // Remove the following line if you don't want automatic content compression.
  25.           pipeline.addLast("deflater", new HttpContentCompressor());
  26.           pipeline.addLast("handler", new HttpRequestHandler());
  27.           return pipeline;
  28.       }
  29.   }
HttpRequestHandler.java

点击(此处)折叠或打开

  1. package org.jboss.netty.example.http.snoop;
  2.    
  3.   import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
  4.   import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
  5.   import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
  6.   import static org.jboss.netty.handler.codec.http.HttpVersion.*;
  7.    
  8.   import java.util.List;
  9.   import java.util.Map;
  10.   import java.util.Map.Entry;
  11.   import java.util.Set;
  12.    
  13.   import org.jboss.netty.buffer.ChannelBuffer;
  14.   import org.jboss.netty.buffer.ChannelBuffers;
  15.   import org.jboss.netty.channel.ChannelFuture;
  16.   import org.jboss.netty.channel.ChannelFutureListener;
  17.   import org.jboss.netty.channel.ChannelHandlerContext;
  18.   import org.jboss.netty.channel.ExceptionEvent;
  19.   import org.jboss.netty.channel.MessageEvent;
  20.   import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
  21.   import org.jboss.netty.handler.codec.http.Cookie;
  22.   import org.jboss.netty.handler.codec.http.CookieDecoder;
  23.   import org.jboss.netty.handler.codec.http.CookieEncoder;
  24.   import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
  25.   import org.jboss.netty.handler.codec.http.HttpChunk;
  26.   import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
  27.   import org.jboss.netty.handler.codec.http.HttpRequest;
  28.   import org.jboss.netty.handler.codec.http.HttpResponse;
  29.   import org.jboss.netty.handler.codec.http.QueryStringDecoder;
  30.   import org.jboss.netty.util.CharsetUtil;
  31.    
  32.   /**
  33.    * @author <a href="http://www.jboss.org/netty/">The Netty Project
  34.    * @author Andy Taylor (andy.taylor@jboss.org)
  35.    * @author <a href="http://gleamynode.net/">Trustin Lee
  36.    *
  37.    * @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $
  38.    */
  39.   public class HttpRequestHandler extends SimpleChannelUpstreamHandler {
  40.    
  41.       private HttpRequest request;
  42.       private boolean readingChunks;
  43.       /** Buffer that stores the response content */
  44.       private final StringBuilder buf = new StringBuilder();
  45.    
  46.       @Override
  47.       public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  48.           if (!readingChunks) {
  49.               HttpRequest request = this.request = (HttpRequest) e.getMessage();
  50.    
  51.               if (is100ContinueExpected(request)) {
  52.                   send100Continue(e);
  53.               }
  54.    
  55.               buf.setLength(0);
  56.               buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
  57.               buf.append("===================================\r\n");
  58.    
  59.               buf.append("VERSION: " + request.getProtocolVersion() + "\r\n");
  60.               buf.append("HOSTNAME: " + getHost(request, "unknown") + "\r\n");
  61.               buf.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
  62.    
  63.               for (Map.Entry<String, String> h: request.getHeaders()) {
  64.                   buf.append("HEADER: " + h.getKey() + " = " + h.getValue() + "\r\n");
  65.               }
  66.               buf.append("\r\n");
  67.    
  68.               QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
  69.               Map<String, List<String>> params = queryStringDecoder.getParameters();
  70.               if (!params.isEmpty()) {
  71.                   for (Entry<String, List<String>> p: params.entrySet()) {
  72.                       String key = p.getKey();
  73.                       List<String> vals = p.getValue();
  74.                       for (String val : vals) {
  75.                           buf.append("PARAM: " + key + " = " + val + "\r\n");
  76.                       }
  77.                   }
  78.                   buf.append("\r\n");
  79.               }
  80.    
  81.               if (request.isChunked()) {
  82.                   readingChunks = true;
  83.               } else {
  84.                   ChannelBuffer content = request.getContent();
  85.                  if (content.readable()) {
  86.                      buf.append("CONTENT: " + content.toString(CharsetUtil.UTF_8) + "\r\n");
  87.                  }
  88.                  writeResponse(e);
  89.              }
  90.          } else {
  91.              HttpChunk chunk = (HttpChunk) e.getMessage();
  92.              if (chunk.isLast()) {
  93.                  readingChunks = false;
  94.                  buf.append("END OF CONTENT\r\n");
  95.   
  96.                  HttpChunkTrailer trailer = (HttpChunkTrailer) chunk;
  97.                  if (!trailer.getHeaderNames().isEmpty()) {
  98.                      buf.append("\r\n");
  99.                      for (String name: trailer.getHeaderNames()) {
  100.                          for (String value: trailer.getHeaders(name)) {
  101.                              buf.append("TRAILING HEADER: " + name + " = " + value + "\r\n");
  102.                          }
  103.                      }
  104.                      buf.append("\r\n");
  105.                  }
  106.   
  107.                  writeResponse(e);
  108.              } else {
  109.                  buf.append("CHUNK: " + chunk.getContent().toString(CharsetUtil.UTF_8) + "\r\n");
  110.              }
  111.          }
  112.      }
  113.   
  114.      private void writeResponse(MessageEvent e) {
  115.          // Decide whether to close the connection or not.
  116.          boolean keepAlive = isKeepAlive(request);
  117.   
  118.          // Build the response object.
  119.          HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  120.          response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
  121.          response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  122.   
  123.          if (keepAlive) {
  124.              // Add 'Content-Length' header only for a keep-alive connection.
  125.              response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
  126.          }
  127.   
  128.          // Encode the cookie.
  129.          String cookieString = request.getHeader(COOKIE);
  130.          if (cookieString != null) {
  131.              CookieDecoder cookieDecoder = new CookieDecoder();
  132.              Set<Cookie> cookies = cookieDecoder.decode(cookieString);
  133.              if(!cookies.isEmpty()) {
  134.                  // Reset the cookies if necessary.
  135.                  CookieEncoder cookieEncoder = new CookieEncoder(true);
  136.                  for (Cookie cookie : cookies) {
  137.                      cookieEncoder.addCookie(cookie);
  138.                  }
  139.                  response.addHeader(SET_COOKIE, cookieEncoder.encode());
  140.              }
  141.          }
  142.   
  143.          // Write the response.
  144.          ChannelFuture future = e.getChannel().write(response);
  145.   
  146.          // Close the non-keep-alive connection after the write operation is done.
  147.          if (!keepAlive) {
  148.              future.addListener(ChannelFutureListener.CLOSE);
  149.          }
  150.      }
  151.   
  152.      private void send100Continue(MessageEvent e) {
  153.          HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
  154.          e.getChannel().write(response);
  155.      }
  156.   
  157.      @Override
  158.      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
  159.              throws Exception {
  160.          e.getCause().printStackTrace();
  161.          e.getChannel().close();
  162.      }
  163. }
DatabaseUtil.java

点击(此处)折叠或打开

  1. package org.jboss.netty.example.http.snoop;

  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;

  7. import org.apache.commons.dbcp.BasicDataSource;

  8. /**
  9. * 连接和使用数据库资源的工具类
  10. *
  11. * @author yifangyou
  12. * @version gtm 2010-09-27
  13. */
  14. public class DatabaseUtil {

  15.     /**
  16.      * 数据源
  17.      */
  18.     private BasicDataSource dataSource;
  19.      
  20.     /**
  21.      * 数据库连接
  22.      */
  23.     public Connection conn;

  24.     /**
  25.      * 获取数据源
  26.      * @return 数据源
  27.      */
  28.     public BasicDataSource getDataSource() {
  29.         return dataSource;
  30.     }

  31.     /**
  32.      * 设置数据源
  33.      * @param dataSource 数据源
  34.      */
  35.     public void setDataSource(BasicDataSource dataSource) {
  36.         this.dataSource = dataSource;
  37.     }
  38.      
  39.      
  40.     /**
  41.      * 获取数据库连接
  42.      * @return conn
  43.      */
  44.     public Connection getConnection() {
  45.         try {
  46.             conn = dataSource.getConnection();
  47.         } catch (Exception e) {
  48.             e.printStackTrace();
  49.             return null;
  50.         }
  51.         return conn;
  52.     }
  53.      
  54.     /**
  55.      * 关闭数据库连接
  56.      * @param conn
  57.      */
  58.     public void closeConnection(Connection conn) {
  59.         if (null != conn) {
  60.             try {
  61.                 conn.close();
  62.                 conn = null;
  63.             } catch (SQLException e) {
  64.                 e.printStackTrace();
  65.             }
  66.         }
  67.     }

  68.      
  69.      
  70.     /**
  71.      * 获取执行SQL的工具
  72.      * @param conn 数据库连接
  73.      * @param sql SQL语句
  74.      * @return prepStmt
  75.      */
  76.     public PreparedStatement getPrepStatement(Connection conn, String sql) {
  77.         PreparedStatement prepStmt = null;
  78.         try {
  79.             prepStmt = conn.prepareStatement(sql);
  80.         } catch (SQLException e) {
  81.             e.printStackTrace();
  82.         }
  83.         return prepStmt;
  84.     }
  85.      
  86.      
  87.     /**
  88.      * 关闭数据库资源
  89.      * @param prepStmt
  90.      */
  91.     public void closePrepStatement(PreparedStatement prepStmt) {
  92.         if (null != prepStmt) {
  93.             try {
  94.                 prepStmt.close();
  95.                 prepStmt = null;
  96.             } catch (SQLException e) {
  97.                 e.printStackTrace();
  98.             }
  99.         }
  100.     }

  101. }
2.2 导入jar包
在工程下添加lib目录
把jar包拷进去
点击工程的右键“propertis”->Java Build Path->Libraries->Add JARS
3.分析如何注入
Netty的运行过程是
因此我们需要
Spring注入入口在HttpServer里的main函数
把HttpRequestHandler注入到HttpServerPipelineFactory,
把HttpServerPipelineFactory注入到HttpServer
另外我们在HttpRequestHandler需要用到mysql连接池,因此还要把mysql连接池注入到HttpRequestHandler

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值