netty里集成spring注入mysq连接池(二)

3.实现注入
3.1构建applicationContext.xml
在src目录下建立applicationContext.xml

 


  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.         xmlns:aop="http://www.springframework.org/schema/aop" 
  5.         xmlns:tx="http://www.springframework.org/schema/tx" 
  6.         xsi:schemaLocation="  
  7.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  9.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
  10. </beans> 

3.1构建注入开始点
在HttpServer.java里加入

 


  1. private BeanFactory beanFactory;  
  2.  
  3.     public HttpServer() {  
  4.         ClassPathResource classPathResource = new ClassPathResource(  
  5.                 "applicationContext.xml");  
  6.         beanFactory = new XmlBeanFactory(classPathResource);  
  7.     }  
  8.     public Object getBean(String beenName){  
  9.         return beanFactory.getBean(beenName);  
  10.     }  

3.2注入HttpServerPipelineFactory
在applicationContext.xml里加入

 


  1. <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype"> 
  2. </bean> 

修改HttpServer.java的main函数

 


  1. public static void main(String[] args) {  
  2.     // Configure the server.  
  3.     ServerBootstrap bootstrap = new ServerBootstrap(  
  4.             new NioServerSocketChannelFactory(  
  5.                     Executors.newCachedThreadPool(),  
  6.                     Executors.newCachedThreadPool()));  
  7.     HttpServer httpServer = new HttpServer();  
  8. /       提取httpServerPipelineFactory  
  9.     HttpServerPipelineFactory httpServerPipelineFactory=(HttpServerPipelineFactory)httpServer.getBean("httpServerPipelineFactory");  
  10.     // Set up the event pipeline factory.  
  11.     bootstrap.setPipelineFactory(httpServerPipelineFactory);  
  12.  
  13.     // Bind and start to accept incoming connections.  
  14.     bootstrap.bind(new InetSocketAddress(8081));  
  15. }  

3.3HttpServerPipelineFactory注入HttpRequestHandler
把applicationContext.xml里beans内容改为
 


  1. <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype"> 
  2.         <property name="httpRequestHandler" ref="httpRequestHandler" /> 
  3.      </bean> 
  4.      <bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype"> 
  5.      </bean> 

修改HttpServerPipelineFactory.java的main函数

 


  1. public class HttpServerPipelineFactory implements ChannelPipelineFactory {  
  2.     private HttpRequestHandler httpRequestHandler;  
  3.  
  4.     public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) {  
  5.         this.httpRequestHandler = httpRequestHandler;  
  6.     }  
  7.  
  8.     public HttpRequestHandler getHttpRequestHandler() {  
  9.         return httpRequestHandler;  
  10.     }  
  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 =  
  17.         // SecureChatSslContextFactory.getServerContext().createSSLEngine();  
  18.         // engine.setUseClientMode(false);  
  19.         // pipeline.addLast("ssl", new SslHandler(engine));  
  20.  
  21.         pipeline.addLast("decoder"new HttpRequestDecoder());  
  22.         // Uncomment the following line if you don't want to handle HttpChunks.  
  23.         // pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));  
  24.         pipeline.addLast("encoder"new HttpResponseEncoder());  
  25.         // Remove the following line if you don't want automatic content  
  26.         // compression.  
  27.         pipeline.addLast("deflater"new HttpContentCompressor());  
  28.         pipeline.addLast("handler", httpRequestHandler);  
  29.         return pipeline;  
  30.     }  
  31. }  

3.3HttpRequestHandler注入mysql连接池
把applicationContext.xml里beans内容改为

 


  1.  <?xml version="1.0" encoding="UTF-8"?> 
  2.  
  3. <!--  
  4.   - Application context definition for JPetStore's business layer.  
  5.   - Contains bean references to the transaction manager and to the DAOs in  
  6.   - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").  
  7.   --> 
  8. <beans xmlns="http://www.springframework.org/schema/beans" 
  9.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  10.         xmlns:aop="http://www.springframework.org/schema/aop" 
  11.         xmlns:tx="http://www.springframework.org/schema/tx" 
  12.         xsi:schemaLocation="  
  13.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  14.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  15.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
  16.    
  17.       <!-- =================================== 配置Spring数据源 ========================================= --> 
  18.         <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"         
  19.             destroy-method="close">         
  20.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />          
  21.         <property name="url" value="jdbc:mysql://192.168.13.105:3306/gslb?useUnicode=true&amp;characterEncoding=utf-8" />        
  22.         <property name="username" value="gslb" />        
  23.         <property name="password" value="testpass" />   
  24.         <property name="maxIdle" value="10"/> 
  25.         <property name="maxActive" value="100"/> 
  26.         <property name="maxWait" value="10000"/> 
  27.         <property name="validationQuery" value="select 1"/> 
  28.         <property name="testOnBorrow" value="false"/> 
  29.         <property name="testWhileIdle" value="true"/> 
  30.         <property name="timeBetweenEvictionRunsMillis" value="1200000"/> 
  31.         <property name="minEvictableIdleTimeMillis" value="1800000"/> 
  32.         <property name="numTestsPerEvictionRun" value="5"/> 
  33.         <property name="defaultAutoCommit" value="true"/> 
  34.     </bean> 
  35.     <!--   
  36.         BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性,  
  37.         以便Spring容器关闭时,数据源能够正常关闭。除以上必须的数据源属性外,  
  38.          还有一些常用的属性:   
  39.         defaultAutoCommit:设置从数据源中返回的连接是否采用自动提交机制,默认值为 true;   
  40.         defaultReadOnly:设置数据源是否仅能执行只读操作, 默认值为 false;   
  41.         maxActive:最大连接数据库连接数,设置为0时,表示没有限制;   
  42.         maxIdle:最大等待连接中的数量,设置为0时,表示没有限制;   
  43.         maxWait:最大等待秒数,单位为毫秒, 超过时间会报出错误信息;   
  44.         validationQuery:用于验证连接是否成功的查询SQL语句,SQL语句必须至少要返回一行数据,  
  45.                           如你可以简单地设置为:“select count(*) from user”;   
  46.         removeAbandoned:是否自我中断,默认是 false ;   
  47.         removeAbandonedTimeout:几秒后数据连接会自动断开,在removeAbandoned为true,提供该值;   
  48.         logAbandoned:是否记录中断事件, 默认为 false;  
  49.      --> 
  50.     <bean id="databaseUtil" class="org.jboss.netty.example.http.snoop.DatabaseUtil"> 
  51.         <property name="dataSource" ref="dataSource" /> 
  52.     </bean> 
  53.      <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype"> 
  54.         <property name="httpRequestHandler" ref="httpRequestHandler" /> 
  55.      </bean> 
  56.      <bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype"> 
  57.         <property name="databaseUtil" ref="databaseUtil" /> 
  58.      </bean>   
  59. </beans> 

修改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.sql.Connection;  
  9. import java.sql.PreparedStatement;  
  10. import java.sql.ResultSet;  
  11.   import java.util.List;  
  12.   import java.util.Map;  
  13.   import java.util.Map.Entry;  
  14.   import java.util.Set;  
  15.     
  16.   import org.jboss.netty.buffer.ChannelBuffer;  
  17.   import org.jboss.netty.buffer.ChannelBuffers;  
  18.   import org.jboss.netty.channel.ChannelFuture;  
  19.   import org.jboss.netty.channel.ChannelFutureListener;  
  20.   import org.jboss.netty.channel.ChannelHandlerContext;  
  21.   import org.jboss.netty.channel.ExceptionEvent;  
  22.   import org.jboss.netty.channel.MessageEvent;  
  23.   import org.jboss.netty.channel.SimpleChannelUpstreamHandler;  
  24.   import org.jboss.netty.handler.codec.http.Cookie;  
  25.   import org.jboss.netty.handler.codec.http.CookieDecoder;  
  26.   import org.jboss.netty.handler.codec.http.CookieEncoder;  
  27.   import org.jboss.netty.handler.codec.http.DefaultHttpResponse;  
  28.   import org.jboss.netty.handler.codec.http.HttpChunk;  
  29.   import org.jboss.netty.handler.codec.http.HttpChunkTrailer;  
  30.   import org.jboss.netty.handler.codec.http.HttpRequest;  
  31.   import org.jboss.netty.handler.codec.http.HttpResponse;  
  32. import org.jboss.netty.handler.codec.http.HttpResponseStatus;  
  33.   import org.jboss.netty.handler.codec.http.QueryStringDecoder;  
  34. import org.jboss.netty.util.CharsetUtil;  
  35.     
  36.   /**  
  37.    * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>  
  38.    * @author Andy Taylor (andy.taylor@jboss.org)  
  39.    * @author <a href="http://gleamynode.net/">Trustin Lee</a>  
  40.    *  
  41.    * @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $  
  42.    */ 
  43.   public class HttpRequestHandler extends SimpleChannelUpstreamHandler {  
  44.     
  45.       private DatabaseUtil databaseUtil;  
  46.       private HttpRequest request;  
  47.       private boolean readingChunks;  
  48.       /** Buffer that stores the response content */ 
  49.       private final StringBuilder buf = new StringBuilder();  
  50.     
  51.       @Override 
  52.       public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
  53.  
  54.               System.out.println("messageReceived");  
  55.               HttpRequest request = this.request = (HttpRequest) e.getMessage();  
  56.     
  57.               buf.setLength(0);  
  58.               QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());  
  59.               Map<String, List<String>> params = queryStringDecoder.getParameters();  
  60.                 
  61.               if (!params.isEmpty()) {  
  62.                   HttpResponseStatus httpResponseStatus=HttpResponseStatus.OK;  
  63.                     
  64.                   if(params.containsKey("username")){  
  65.                       if(params.containsKey("password")){  
  66.                           List<String> values=params.get("username");  
  67.                           String username="";  
  68.                           if(values.size()>0){  
  69.                               username=values.get(0);  
  70.                           }  
  71.                           values=params.get("password");  
  72.                           String password="";  
  73.                           if(values.size()>0){  
  74.                               password=values.get(0);  
  75.                           }  
  76.                           try{  
  77.                               Connection conn=databaseUtil.getConnection();  
  78.                               if(conn!=null){  
  79.                                   //查询用户名和密码是否匹配  
  80.                                   PreparedStatement ps=databaseUtil.getPrepStatement(conn,"select count(*) from user where name=? and password=?");  
  81.                                   ps.setString(1, username);  
  82.                                   ps.setString(2, password);  
  83.                                   ResultSet rs=ps.executeQuery();  
  84.                                   if(rs.next()){  
  85.                                       if(rs.getInt(1)>0){  
  86.                                           buf.append("FOUND");    
  87.                                       }else{  
  88.                                           buf.append("FOUND");   
  89.                                       }  
  90.                                   }else{  
  91.                                       buf.append("QUERY ERROR");   
  92.                                   }  
  93.                                   databaseUtil.closeResultSet(rs);  
  94.                                   databaseUtil.closePrepStatement(ps);  
  95.                                   databaseUtil.closeConnection(conn);  
  96.                               }else{  
  97.                                   buf.append("connot connect mysql");  
  98.                               }  
  99.                           }catch(Exception e1){  
  100.                               e1.printStackTrace();  
  101.                               buf.append("QUERY ERROR");   
  102.                           }    
  103.                       }else{  
  104.                           buf.append("miss password");  
  105.                       }  
  106.                   }else{  
  107.                       buf.append("miss username");  
  108.                   }         
  109.                   writeResponse(e,httpResponseStatus,buf);  
  110.               }else{  
  111.                   buf.append("miss username and password");  
  112.                   writeResponse(e,OK,buf);  
  113.               }  
  114.      }  
  115.    
  116.      private void writeResponse(MessageEvent e,HttpResponseStatus httpResponseStatus,StringBuilder buf) {  
  117.          // Decide whether to close the connection or not.  
  118.          boolean keepAlive = isKeepAlive(request);  
  119.    
  120.          // Build the response object.  
  121.          HttpResponse response = new DefaultHttpResponse(HTTP_1_1, httpResponseStatus);  
  122.          response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));  
  123.          response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");  
  124.    
  125.          // Write the response.  
  126.          ChannelFuture future = e.getChannel().write(response);  
  127.    
  128.          // Close the non-keep-alive connection after the write operation is done.  
  129.          future.addListener(ChannelFutureListener.CLOSE);  
  130.      }  
  131.    
  132.      private void send100Continue(MessageEvent e) {  
  133.          HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);  
  134.          e.getChannel().write(response);  
  135.      }  
  136.    
  137.      @Override 
  138.      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)  
  139.              throws Exception {  
  140.          e.getCause().printStackTrace();  
  141.          e.getChannel().close();  
  142.      }  
  143.  
  144.     public void setDatabaseUtil(DatabaseUtil databaseUtil) {  
  145.         this.databaseUtil = databaseUtil;  
  146.     }  
  147.  
  148.     public DatabaseUtil getDatabaseUtil() {  
  149.         return databaseUtil;  
  150.     }  
  151.  }  

4.测试
访问
http://127.0.0.1:8081/sdf?username=test1&password=1bbd886460827015e5d605ed44252221获得FOUND即可
 

netty里集成spring注入mysq连接池(二)

 项目源代码见:http://down.51cto.com/data/227126





     本文转自yifangyou 51CTO博客,原文链接:http://blog.51cto.com/yifangyou/622608,如需转载请自行联系原作者




上一篇:springboot启动时禁用数据库连接检测


下一篇:教你解决微信跳转appstore的困扰