Jedis是官方推荐的连接redius的客户端,之所以没有使用redis的jdbc的原因是:
1) redis的jdbc的set方法有问题,set字符串,但是取出来的却是字符串长度
2)redis的jdbc的性能低并且不稳定,网上有人做测试证明过。
1.准备好需要的jar包
- spring.jar //spring包
- netty-3.2.4.Final.jar // netty库
- commons-dbcp.jar // dbcp数据库连接池
- mysql-connector-java-5.1.6.jar // dbcp数据库连接池需要依赖
- commons-logging.jar //spring.jar需要依赖
- commons-pool.jar // dbcp数据库连接池需要依赖
- jedis-2.0.0.jar //jedis包
2.新建java工程TestNettyServer并添加spring
3.注入jedis
3.1构建访问redis通用类
在RedisUtil.java里加入
- import redis.clients.jedis.ShardedJedis;
- import redis.clients.jedis.ShardedJedisPool;
- /**
- * 连接和使用数据库资源的工具类
- *
- * @author yifangyou
- * @version IAM 2011-07-27
- */
- public class RedisUtil {
- /**
- * 数据源
- */
- private ShardedJedisPool shardedJedisPool;
- /**
- * 获取数据库连接
- * @return conn
- */
- public ShardedJedis getConnection() {
- ShardedJedis jedis=null;
- try {
- jedis=shardedJedisPool.getResource();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return jedis;
- }
- /**
- * 关闭数据库连接
- * @param conn
- */
- public void closeConnection(ShardedJedis jedis) {
- if (null != jedis) {
- try {
- shardedJedisPool.returnResource(jedis);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 设置数据
- * @param conn
- */
- public boolean setData(String key,String value) {
- try {
- ShardedJedis jedis=shardedJedisPool.getResource();
- jedis.set(key,value);
- shardedJedisPool.returnResource(jedis);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
- /**
- * 获取数据
- * @param conn
- */
- public String getData(String key) {
- String value=null;
- try {
- ShardedJedis jedis=shardedJedisPool.getResource();
- value=jedis.get(key);
- shardedJedisPool.returnResource(jedis);
- return value;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return value;
- }
- /**
- * 设置连接池
- * @return 数据源
- */
- public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
- this.shardedJedisPool = shardedJedisPool;
- }
- /**
- * 获取连接池
- * @return 数据源
- */
- public ShardedJedisPool getShardedJedisPool() {
- return shardedJedisPool;
- }
- }
3.2HttpRequestHandler注入jedis
在applicationContext.xml里加入
- <!-- POOL配置 -->
- <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
- <property name="maxActive" value="20" />
- <property name="maxIdle" value="10" />
- <property name="maxWait" value="1000" />
- <property name="testOnBorrow" value="true"/>
- </bean>
- <!-- jedis shard信息配置 -->
- <bean id="jedis.shardInfo" class="redis.clients.jedis.JedisShardInfo">
- <constructor-arg index="0" value="122.49.26.60" />
- <constructor-arg index="1" value="6379" />
- </bean>
- <!-- jedis shard pool配置 -->
- <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
- <constructor-arg index="0" ref="jedisPoolConfig" />
- <constructor-arg index="1">
- <list>
- <ref bean="jedis.shardInfo" />
- </list>
- </constructor-arg>
- </bean>
- <bean id="redisUtil" class="org.jboss.netty.example.http.snoop.RedisUtil">
- <property name="shardedJedisPool" ref="shardedJedisPool" />
- </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" />
- <property name="redisUtil" ref="redisUtil" />
- </bean>
4.测试
访问
http://127.0.0.1:8081/sfds?username=yifangyou
源码下载:http://down.51cto.com/data/229434
修改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 ([email protected])
- * @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 RedisUtil redisUtil;
- private HttpRequest request;
- /** Buffer that stores the response content */
- private final StringBuilder buf = new StringBuilder();
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
- HttpRequest request = this.request = (HttpRequest) e.getMessage();
- redisUtil.setData("yifangyou", "testpassword");
- 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")){
- List<String> values=params.get("username");
- String username="";
- if(values.size()>0){
- username=values.get(0);
- }
- String password=redisUtil.getData(username);
- if(password==null){
- buf.append("not found ");
- }else{
- buf.append(username+"'s password is:"+password);
- }
- }else{
- buf.append("miss username");
- }
- writeResponse(e,httpResponseStatus,buf);
- }else{
- buf.append("miss username");
- 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;
- }
- public void setRedisUtil(RedisUtil redisUtil) {
- this.redisUtil = redisUtil;
- }
- public RedisUtil getRedisUtil() {
- return redisUtil;
- }
- }
本文出自 “一方有” 博客,请务必保留此出处http://yifangyou.blog.51cto.com/900206/628163