3.实现注入
3.1构建applicationContext.xml
在src目录下建立applicationContext.xml
点击(此处)折叠或打开
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- </beans>
在HttpServer.java里加入
点击(此处)折叠或打开
- private BeanFactory beanFactory;
- public HttpServer() {
- ClassPathResource classPathResource = new ClassPathResource(
- "applicationContext.xml");
- beanFactory = new XmlBeanFactory(classPathResource);
- }
- public Object getBean(String beenName){
- return beanFactory.getBean(beenName);
- }
在applicationContext.xml里加入
点击(此处)折叠或打开
- <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype">
- </bean>
点击(此处)折叠或打开
- public static void main(String[] args) {
- // Configure the server.
- ServerBootstrap bootstrap = new ServerBootstrap(
- new NioServerSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- HttpServer httpServer = new HttpServer();
- / 提取httpServerPipelineFactory
- HttpServerPipelineFactory httpServerPipelineFactory=(HttpServerPipelineFactory)httpServer.getBean("httpServerPipelineFactory");
- // Set up the event pipeline factory.
- bootstrap.setPipelineFactory(httpServerPipelineFactory);
- // Bind and start to accept incoming connections.
- bootstrap.bind(new InetSocketAddress(8081));
- }
把applicationContext.xml里beans内容改为
点击(此处)折叠或打开
- <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype">
- <property name="httpRequestHandler" ref="httpRequestHandler" />
- </bean>
- <bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype">
- </bean>
修改HttpServerPipelineFactory.java的main函数
点击(此处)折叠或打开
- public class HttpServerPipelineFactory implements ChannelPipelineFactory {
- private HttpRequestHandler httpRequestHandler;
- public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) {
- this.httpRequestHandler = httpRequestHandler;
- }
- public HttpRequestHandler getHttpRequestHandler() {
- return httpRequestHandler;
- }
- public ChannelPipeline getPipeline() throws Exception {
- // Create a default pipeline implementation.
- ChannelPipeline pipeline = pipeline();
- // Uncomment the following line if you want HTTPS
- // SSLEngine engine =
- // SecureChatSslContextFactory.getServerContext().createSSLEngine();
- // engine.setUseClientMode(false);
- // pipeline.addLast("ssl", new SslHandler(engine));
- pipeline.addLast("decoder", new HttpRequestDecoder());
- // Uncomment the following line if you don't want to handle HttpChunks.
- // pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
- pipeline.addLast("encoder", new HttpResponseEncoder());
- // Remove the following line if you don't want automatic content
- // compression.
- pipeline.addLast("deflater", new HttpContentCompressor());
- pipeline.addLast("handler", httpRequestHandler);
- return pipeline;
- }
- }
把applicationContext.xml里beans内容改为
点击(此处)折叠或打开
- <?xml version="1.0" encoding="UTF-8"?>
- <!--
- - Application context definition for JPetStore's business layer.
- - Contains bean references to the transaction manager and to the DAOs in
- - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
- -->
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <!-- =================================== 配置Spring数据源 ========================================= -->
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://192.168.13.105:3306/gslb?useUnicode=true&characterEncoding=utf-8" />
- <property name="username" value="gslb" />
- <property name="password" value="testpass" />
- <property name="maxIdle" value="10"/>
- <property name="maxActive" value="100"/>
- <property name="maxWait" value="10000"/>
- <property name="validationQuery" value="select 1"/>
- <property name="testOnBorrow" value="false"/>
- <property name="testWhileIdle" value="true"/>
- <property name="timeBetweenEvictionRunsMillis" value="1200000"/>
- <property name="minEvictableIdleTimeMillis" value="1800000"/>
- <property name="numTestsPerEvictionRun" value="5"/>
- <property name="defaultAutoCommit" value="true"/>
- </bean>
- <!--
- BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性,
- 以便Spring容器关闭时,数据源能够正常关闭。除以上必须的数据源属性外,
- 还有一些常用的属性:
- defaultAutoCommit:设置从数据源中返回的连接是否采用自动提交机制,默认值为 true;
- defaultReadOnly:设置数据源是否仅能执行只读操作, 默认值为 false;
- maxActive:最大连接数据库连接数,设置为0时,表示没有限制;
- maxIdle:最大等待连接中的数量,设置为0时,表示没有限制;
- maxWait:最大等待秒数,单位为毫秒, 超过时间会报出错误信息;
- validationQuery:用于验证连接是否成功的查询SQL语句,SQL语句必须至少要返回一行数据,
- 如你可以简单地设置为:“select count(*) from user”;
- removeAbandoned:是否自我中断,默认是 false ;
- removeAbandonedTimeout:几秒后数据连接会自动断开,在removeAbandoned为true,提供该值;
- logAbandoned:是否记录中断事件, 默认为 false;
- -->
- <bean id="databaseUtil" class="org.jboss.netty.example.http.snoop.DatabaseUtil">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype">
- <property name="httpRequestHandler" ref="httpRequestHandler" />
- </bean>
- <bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype">
- <property name="databaseUtil" ref="databaseUtil" />
- </bean>
- </beans>
点击(此处)折叠或打开
- package org.jboss.netty.example.http.snoop;
- import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
- import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
- import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
- import static org.jboss.netty.handler.codec.http.HttpVersion.*;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import org.jboss.netty.buffer.ChannelBuffer;
- import org.jboss.netty.buffer.ChannelBuffers;
- import org.jboss.netty.channel.ChannelFuture;
- import org.jboss.netty.channel.ChannelFutureListener;
- import org.jboss.netty.channel.ChannelHandlerContext;
- import org.jboss.netty.channel.ExceptionEvent;
- import org.jboss.netty.channel.MessageEvent;
- import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
- import org.jboss.netty.handler.codec.http.Cookie;
- import org.jboss.netty.handler.codec.http.CookieDecoder;
- import org.jboss.netty.handler.codec.http.CookieEncoder;
- import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
- import org.jboss.netty.handler.codec.http.HttpChunk;
- import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
- import org.jboss.netty.handler.codec.http.HttpRequest;
- import org.jboss.netty.handler.codec.http.HttpResponse;
- import org.jboss.netty.handler.codec.http.HttpResponseStatus;
- import org.jboss.netty.handler.codec.http.QueryStringDecoder;
- import org.jboss.netty.util.CharsetUtil;
- /**
- * @author <a href="http://www.jboss.org/netty/">The Netty Project
- * @author Andy Taylor (andy.taylor@jboss.org)
- * @author <a href="http://gleamynode.net/">Trustin Lee
- *
- * @version $Rev: 2368 $, $Date: 2010-10-18 17:19:03 +0900 (Mon, 18 Oct 2010) $
- */
- public class HttpRequestHandler extends SimpleChannelUpstreamHandler {
- private DatabaseUtil databaseUtil;
- private HttpRequest request;
- private boolean readingChunks;
- /** Buffer that stores the response content */
- private final StringBuilder buf = new StringBuilder();
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
- System.out.println("messageReceived");
- HttpRequest request = this.request = (HttpRequest) e.getMessage();
- buf.setLength(0);
- QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
- Map<String, List<String>> params = queryStringDecoder.getParameters();
- if (!params.isEmpty()) {
- HttpResponseStatus httpResponseStatus=HttpResponseStatus.OK;
- if(params.containsKey("username")){
- if(params.containsKey("password")){
- List<String> values=params.get("username");
- String username="";
- if(values.size()>0){
- username=values.get(0);
- }
- values=params.get("password");
- String password="";
- if(values.size()>0){
- password=values.get(0);
- }
- try{
- Connection conn=databaseUtil.getConnection();
- if(conn!=null){
- //查询用户名和密码是否匹配
- PreparedStatement ps=databaseUtil.getPrepStatement(conn,"select count(*) from user where name=? and password=?");
- ps.setString(1, username);
- ps.setString(2, password);
- ResultSet rs=ps.executeQuery();
- if(rs.next()){
- if(rs.getInt(1)>0){
- buf.append("FOUND");
- }else{
- buf.append("FOUND");
- }
- }else{
- buf.append("QUERY ERROR");
- }
- databaseUtil.closeResultSet(rs);
- databaseUtil.closePrepStatement(ps);
- databaseUtil.closeConnection(conn);
- }else{
- buf.append("connot connect mysql");
- }
- }catch(Exception e1){
- e1.printStackTrace();
- buf.append("QUERY ERROR");
- }
- }else{
- buf.append("miss password");
- }
- }else{
- buf.append("miss username");
- }
- writeResponse(e,httpResponseStatus,buf);
- }else{
- buf.append("miss username and password");
- writeResponse(e,OK,buf);
- }
- }
- private void writeResponse(MessageEvent e,HttpResponseStatus httpResponseStatus,StringBuilder buf) {
- // Decide whether to close the connection or not.
- boolean keepAlive = isKeepAlive(request);
- // Build the response object.
- HttpResponse response = new DefaultHttpResponse(HTTP_1_1, httpResponseStatus);
- response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
- response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
- // Write the response.
- ChannelFuture future = e.getChannel().write(response);
- // Close the non-keep-alive connection after the write operation is done.
- future.addListener(ChannelFutureListener.CLOSE);
- }
- private void send100Continue(MessageEvent e) {
- HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
- e.getChannel().write(response);
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
- throws Exception {
- e.getCause().printStackTrace();
- e.getChannel().close();
- }
- public void setDatabaseUtil(DatabaseUtil databaseUtil) {
- this.databaseUtil = databaseUtil;
- }
- public DatabaseUtil getDatabaseUtil() {
- return databaseUtil;
- }
- }
访问
http://127.0.0.1:8081/sdf?username=test1&password=1bbd886460827015e5d605ed44252221获得FOUND即可
相关推荐
Spring 是一个广泛使用的 Java 应用开发框架,尤其在企业级应用中非常流行,它提供了依赖注入、面向切面编程等功能,简化了Java应用的开发。将 Netty 与 Spring 集成,可以利用 Netty 的高性能网络通信能力,同时...
JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA版基于netty的物联网高并发智能网关 JAVA...
本文将深入探讨如何在Netty中集成Spring MVC,并实现MySQL数据库连接池的注入,以构建一个完整的网络应用服务。 首先,我们要理解Netty的基本原理。Netty是一个基于NIO的客户机/服务器通信框架,它提供了一组高度可...
首先,Spring框架是Java领域最流行的后端开发框架之一,它提供了丰富的功能和强大的依赖注入机制。在WebSocket方面,Spring提供了一个名为`Spring Websocket`的模块,使得开发者可以方便地在Spring应用中集成...
综上所述,"Netty+Spring Boot仿微信 全栈开发高性能后台及客户端"项目是一个综合性的学习和实践平台,涵盖了网络编程、后端开发、全栈集成以及性能优化等多个领域。通过这个项目,开发者不仅可以提升自己的技术能力...
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是现代Java开发中用于构建反应式应用程序的关键组件。Spring Reactor是响应式流(Reactive Streams)规范的实现,它提供了用于处理异步事件和数据...
Netty和Spring是两个在Java开发领域非常重要的框架。Netty是一个高性能、异步事件驱动的网络应用程序框架,常用于创建高并发、低延迟的网络服务,如TCP、UDP等协议的应用。Spring则是一个全面的企业级应用开发框架,...
Spring Netty项目是一个整合了Netty 4和Spring 5框架的应用示例,它展示了如何在Netty服务器中使用Spring的特性,特别是针对UDP通信、MyBatis持久化以及通过Netty Handler访问Spring Bean来实现数据库操作。...
SpringBoot和Netty都是Java开发领域中的重要工具。SpringBoot以其快速、简洁的特性,极大地简化了Spring应用的初始搭建以及开发过程,而Netty则是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的...
在Java端,Netty是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。利用Netty,我们可以轻松实现TCP服务器,创建ServerBootstrap,配置通道处理器pipeline,监听客户端...
Spring Boot 是一个流行的Java开发框架,它简化了创建独立、生产级别的基于Spring的应用程序的流程。Netty 是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。整合...
Java物联网的Netty服务器是一种基于Java的高性能网络应用框架,主要应用于开发高并发、低延迟的网络服务。Netty由JBOSS组织开发并维护,是Java生态系统中的一个强大工具,广泛用于物联网(IoT)场景,如设备通信、数据...
iot-ucy是基于netty, spring boot等框架实现的物联网中间件, 已支持tcp、udp、mqtt、mqtt网关、websocket、modbus、dtu适配(AT协议)、dtu+modbus(tcp和rtu) 适配,plc (西门子, 欧姆龙),串口等常用物联网协议,并且...
Spring 是一个广泛使用的Java企业级应用开发框架,提供依赖注入、面向切面编程等功能。在这个项目中,Spring 可能被用来管理服务组件,如网络监听器(基于Netty)、视频处理逻辑(使用JavaCV)以及与RTMP服务器的...
Spring是一个全面的Java应用框架,提供强大的依赖注入、AOP(面向切面编程)以及丰富的功能模块;Netty则是一个高性能、异步事件驱动的网络应用程序框架,常用于构建高并发、低延迟的网络服务;MyBatis是一个持久层...
在Java编程环境中,Netty是一个高性能、异步事件驱动的网络应用程序框架,常用于构建可伸缩、高并发的服务器。本示例关注的是如何利用Netty实现一个基于UDP(User Datagram Protocol)的数据接收服务,这在需要进行...
### 使用Java NIO实现异步连接池的关键知识点 #### 异步连接池的诞生背景与重要性 在现代Web应用程序开发中,为了提升系统性能和响应速度,常连接与连接池技术成为不可或缺的一部分。常连接是指一个持久存在的TCP...
通过以上步骤,我们可以构建出一个强大的基于Java的后端服务架构,集成了Spring Boot的易用性、Dubbo的分布式服务治理和Netty的高性能网络通信能力。这种架构适用于大型、复杂的企业级应用,能够提供高效、稳定的...