您的位置:首页 > 编程语言 > Java开发

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

2011-07-25 11:20 169 查看
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>

3.1构建注入开始点

在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);
}

3.2注入HttpServerPipelineFactory

在applicationContext.xml里加入

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

修改HttpServer.java的main函数

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));
}

3.3HttpServerPipelineFactory注入HttpRequestHandler

把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;
}
}

3.3HttpRequestHandler注入mysql连接池

把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>

修改HttpRequestHandler.java

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</a>
* @author Andy Taylor (andy.taylor@jboss.org)
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
*
* @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;
}
}

4.测试

访问

http://127.0.0.1:8081/sdf?username=test1&password=1bbd886460827015e5d605ed44252221获得FOUND即可





项目源代码见:http://down.51cto.com/data/227126
本文出自 “一方有” 博客,请务必保留此出处http://yifangyou.blog.51cto.com/900206/622608
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: