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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介:

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即可
 

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





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




相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
|
Java Spring 容器
Spring系列文章:Spring6集成MyBatis3.5
Spring系列文章:Spring6集成MyBatis3.5
|
2月前
|
XML Java 开发者
Spring Boot中的bean注入方式和原理
Spring Boot中的bean注入方式和原理
119 0
|
15天前
|
安全 Java 测试技术
Spring Boot集成支付宝支付:概念与实战
【4月更文挑战第29天】在电子商务和在线业务应用中,集成有效且安全的支付解决方案是至关重要的。支付宝作为中国领先的支付服务提供商,其支付功能的集成可以显著提升用户体验。本篇博客将详细介绍如何在Spring Boot应用中集成支付宝支付功能,并提供一个实战示例。
36 2
|
3天前
|
NoSQL Java MongoDB
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
【5月更文挑战第11天】本文介绍了如何将非关系型数据库MongoDB与Spring Boot框架集成,以实现高效灵活的数据管理。Spring Boot简化了Spring应用的构建和部署,MongoDB则以其对灵活数据结构的处理能力受到青睐。集成步骤包括:添加MongoDB依赖、配置连接信息、创建数据访问对象(DAO)以及进行数据操作。通过这种方式,开发者可以充分利用两者优势,应对各种数据需求。在实际应用中,结合微服务架构等技术,可以构建高性能、可扩展的系统。掌握MongoDB与Spring Boot集成对于提升开发效率和项目质量至关重要,未来有望在更多领域得到广泛应用。
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
|
6天前
|
安全 Java 数据库连接
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
|
8天前
|
XML Java 数据格式
Spring 属性注入方式
Spring 属性注入方式
13 2
|
20天前
|
Java Spring 容器
Spring注入
Spring注入
31 13
|
1月前
|
缓存 Java Spring
单体项目中资源管理模块集成Spring Cache
该内容是关于将Spring Cache集成到资源管理模块以实现缓存同步的说明。主要策略包括:查询时添加到缓存,增删改时删除相关缓存。示例代码展示了@Service类中使用@Transactional和@Cacheable注解进行缓存操作,以及在RedisTemplate中处理缓存的示例。
24 5
|
1月前
|
JSON Java 数据库连接
属性注入掌握:Spring Boot配置属性的高级技巧与最佳实践
属性注入掌握:Spring Boot配置属性的高级技巧与最佳实践
28 1
|
1月前
|
网络协议 Java 物联网
Spring Boot与Netty打造TCP服务端(解决粘包问题)
Spring Boot与Netty打造TCP服务端(解决粘包问题)
35 1