`

java开发之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
  38.    * @author Andy Taylor (andy.taylor@jboss.org)
  39.    * @author <a href="http://gleamynode.net/">Trustin Lee
  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即可
分享到:
评论

相关推荐

    netty4与spring集成

    Spring 是一个广泛使用的 Java 应用开发框架,尤其在企业级应用中非常流行,它提供了依赖注入、面向切面编程等功能,简化了Java应用的开发。将 Netty 与 Spring 集成,可以利用 Netty 的高性能网络通信能力,同时...

    JAVA版基于netty的物联网高并发智能网关.zip

    JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA...

    netty-spring-mvc-master.rar_netty_netty spring_netty4 spring_s

    本文将深入探讨如何在Netty中集成Spring MVC,并实现MySQL数据库连接池的注入,以构建一个完整的网络应用服务。 首先,我们要理解Netty的基本原理。Netty是一个基于NIO的客户机/服务器通信框架,它提供了一组高度可...

    Spring+Netty+WebSocket实例

    首先,Spring框架是Java领域最流行的后端开发框架之一,它提供了丰富的功能和强大的依赖注入机制。在WebSocket方面,Spring提供了一个名为`Spring Websocket`的模块,使得开发者可以方便地在Spring应用中集成...

    Netty+Spring Boot仿微信 全栈开发高性能后台及客户端

    综上所述,"Netty+Spring Boot仿微信 全栈开发高性能后台及客户端"项目是一个综合性的学习和实践平台,涵盖了网络编程、后端开发、全栈集成以及性能优化等多个领域。通过这个项目,开发者不仅可以提升自己的技术能力...

    基于Java的netty-mqtt MQTT 3.1.1协议服务端与客户端设计源码

    netty-mqtt是一个基于Java开发的MQTT 3.1.1协议服务端与客户端,包含113个文件,其中包括87个Java源文件、8个XML文件、7个Iml文件、3个YAML文件、3个JKS文件、2个Factories文件、1个LICENSE文件和1个Markdown文件。...

    Java编程方法论 之 Spring Reactor Reactor-Netty Spring Webflux 全面解读.pdf

    Java编程方法论中,Spring Reactor、Reactor-Netty和Spring Webflux是现代Java开发中用于构建反应式应用程序的关键组件。Spring Reactor是响应式流(Reactive Streams)规范的实现,它提供了用于处理异步事件和数据...

    netty和spring结合

    Netty和Spring是两个在Java开发领域非常重要的框架。Netty是一个高性能、异步事件驱动的网络应用程序框架,常用于创建高并发、低延迟的网络服务,如TCP、UDP等协议的应用。Spring则是一个全面的企业级应用开发框架,...

    spring-netty.zip

    Spring Netty项目是一个整合了Netty 4和Spring 5框架的应用示例,它展示了如何在Netty服务器中使用Spring的特性,特别是针对UDP通信、MyBatis持久化以及通过Netty Handler访问Spring Bean来实现数据库操作。...

    springboot整合netty的demo

    SpringBoot和Netty都是Java开发领域中的重要工具。SpringBoot以其快速、简洁的特性,极大地简化了Spring应用的初始搭建以及开发过程,而Netty则是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的...

    c++客户端和java(Netty)服务器端tcp通讯

    在Java端,Netty是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。利用Netty,我们可以轻松实现TCP服务器,创建ServerBootstrap,配置通道处理器pipeline,监听客户端...

    spring boot 整合的netty 实现的socket的服务端和客户端

    Spring Boot 是一个流行的Java开发框架,它简化了创建独立、生产级别的基于Spring的应用程序的流程。Netty 是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。整合...

    java物联网的netty服务器

    Java物联网的Netty服务器是一种基于Java的高性能网络应用框架,主要应用于开发高并发、低延迟的网络服务。Netty由JBOSS组织开发并维护,是Java生态系统中的一个强大工具,广泛用于物联网(IoT)场景,如设备通信、数据...

    iot-ucy是使用java语言且基于netty, spring boot, redis等开源项目开发来的物联网网络中间件

    iot-ucy是基于netty, spring boot等框架实现的物联网中间件, 已支持tcp、udp、mqtt、mqtt网关、websocket、modbus、dtu适配(AT协议)、dtu+modbus(tcp和rtu) 适配,plc (西门子, 欧姆龙),串口等常用物联网协议,并且...

    1078解析推流源代码(netty+javacv+spring+maven+rtp+rtmp)

    Spring 是一个广泛使用的Java企业级应用开发框架,提供依赖注入、面向切面编程等功能。在这个项目中,Spring 可能被用来管理服务组件,如网络监听器(基于Netty)、视频处理逻辑(使用JavaCV)以及与RTMP服务器的...

    spring+netty+mybatis整合实例

    Spring是一个全面的Java应用框架,提供强大的依赖注入、AOP(面向切面编程)以及丰富的功能模块;Netty则是一个高性能、异步事件驱动的网络应用程序框架,常用于构建高并发、低延迟的网络服务;MyBatis是一个持久层...

    java实现基于netty 的udp字节数据接收服务

    在Java编程环境中,Netty是一个高性能、异步事件驱动的网络应用程序框架,常用于构建可伸缩、高并发的服务器。本示例关注的是如何利用Netty实现一个基于UDP(User Datagram Protocol)的数据接收服务,这在需要进行...

    用nio实现异步连接池

    ### 使用Java NIO实现异步连接池的关键知识点 #### 异步连接池的诞生背景与重要性 在现代Web应用程序开发中,为了提升系统性能和响应速度,常连接与连接池技术成为不可或缺的一部分。常连接是指一个持久存在的TCP...

    基于java的springboot和dubbo、netty的集成模板

    通过以上步骤,我们可以构建出一个强大的基于Java的后端服务架构,集成了Spring Boot的易用性、Dubbo的分布式服务治理和Netty的高性能网络通信能力。这种架构适用于大型、复杂的企业级应用,能够提供高效、稳定的...

Global site tag (gtag.js) - Google Analytics