`
ssxxjjii
  • 浏览: 932584 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

netty里集成spring注入jedis

 
阅读更多

Jedis是官方推荐的连接redius的客户端,之所以没有使用redisjdbc的原因是:

1) redisjdbcset方法有问题,set字符串,但是取出来的却是字符串长度

2)redisjdbc的性能低并且不稳定,网上有人做测试证明过。

1.准备好需要的jar

 

  1. spring.jar            //spring包  
  2. netty-3.2.4.Final.jar   // netty库  
  3. commons-dbcp.jar    // dbcp数据库连接池  
  4. mysql-connector-java-5.1.6.jar // dbcp数据库连接池需要依赖  
  5. commons-logging.jar  //spring.jar需要依赖  
  6. commons-pool.jar   // dbcp数据库连接池需要依赖  
  7. jedis-2.0.0.jar  //jedis包  

2.新建java工程TestNettyServer并添加spring

详情见《netty里集成spring注入mysq连接池

3.注入jedis

 

3.1构建访问redis通用类

RedisUtil.java里加入

 

  1. import redis.clients.jedis.ShardedJedis;  
  2. import redis.clients.jedis.ShardedJedisPool;  
  3.  
  4.  
  5. /**  
  6.  * 连接和使用数据库资源的工具类  
  7.  *   
  8.  * @author yifangyou  
  9.  * @version IAM 2011-07-27  
  10.  */ 
  11. public class RedisUtil {  
  12.  
  13.     /**  
  14.      * 数据源  
  15.      */ 
  16.     private ShardedJedisPool shardedJedisPool;  
  17.       
  18.     
  19.       
  20.     /**  
  21.      * 获取数据库连接  
  22.      * @return conn  
  23.      */ 
  24.     public ShardedJedis getConnection() {  
  25.         ShardedJedis jedis=null;  
  26.         try {  
  27.             jedis=shardedJedisPool.getResource();  
  28.         } catch (Exception e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.         return jedis;  
  32.     }  
  33.       
  34.     /**  
  35.      * 关闭数据库连接  
  36.      * @param conn  
  37.      */ 
  38.     public void closeConnection(ShardedJedis jedis) {  
  39.         if (null != jedis) {  
  40.             try {  
  41.                 shardedJedisPool.returnResource(jedis);  
  42.             } catch (Exception e) {  
  43.                 e.printStackTrace();  
  44.             }  
  45.         }  
  46.     }  
  47.  
  48.     /**  
  49.      * 设置数据  
  50.      * @param conn  
  51.      */ 
  52.     public boolean setData(String key,String value) {  
  53.             try {  
  54.                 ShardedJedis jedis=shardedJedisPool.getResource();  
  55.                 jedis.set(key,value);  
  56.                 shardedJedisPool.returnResource(jedis);  
  57.                 return true;  
  58.             } catch (Exception e) {  
  59.                 e.printStackTrace();  
  60.                   
  61.             }  
  62.         return false;  
  63.     }  
  64.       
  65.     /**  
  66.      * 获取数据  
  67.      * @param conn  
  68.      */ 
  69.     public String getData(String key) {  
  70.         String value=null;  
  71.             try {  
  72.                 ShardedJedis jedis=shardedJedisPool.getResource();  
  73.                 value=jedis.get(key);  
  74.                 shardedJedisPool.returnResource(jedis);  
  75.                 return value;  
  76.             } catch (Exception e) {  
  77.                 e.printStackTrace();  
  78.                   
  79.             }  
  80.         return value;  
  81.     }  
  82.       
  83.     /**  
  84.      * 设置连接池  
  85.      * @return 数据源  
  86.      */ 
  87.     public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {  
  88.         this.shardedJedisPool = shardedJedisPool;  
  89.     }  
  90.  
  91.     /**  
  92.      * 获取连接池  
  93.      * @return 数据源  
  94.      */ 
  95.     public ShardedJedisPool getShardedJedisPool() {  
  96.         return shardedJedisPool;  
  97.     }     
  98. }  

3.2HttpRequestHandler注入jedis

applicationContext.xml里加入

 

  1.  <!-- POOL配置 --> 
  2. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
  3.     <property name="maxActive"  value="20" /> 
  4.     <property name="maxIdle" value="10" /> 
  5.     <property name="maxWait" value="1000" /> 
  6.     <property name="testOnBorrow"  value="true"/> 
  7. </bean> 
  8.  
  9. <!-- jedis shard信息配置 --> 
  10. <bean id="jedis.shardInfo" class="redis.clients.jedis.JedisShardInfo"> 
  11.     <constructor-arg index="0" value="122.49.26.60" /> 
  12.     <constructor-arg index="1" value="6379" /> 
  13. </bean> 
  14.  
  15. <!-- jedis shard pool配置 --> 
  16. <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"> 
  17.     <constructor-arg index="0" ref="jedisPoolConfig" /> 
  18.     <constructor-arg index="1"> 
  19.         <list> 
  20.             <ref bean="jedis.shardInfo" /> 
  21.         </list> 
  22.     </constructor-arg> 
  23. </bean> 
  24.  <bean id="redisUtil" class="org.jboss.netty.example.http.snoop.RedisUtil"> 
  25.     <property name="shardedJedisPool" ref="shardedJedisPool" /> 
  26. </bean> 
  27.  <bean id="httpServerPipelineFactory" class="org.jboss.netty.example.http.snoop.HttpServerPipelineFactory" scope="prototype"> 
  28.     <property name="httpRequestHandler" ref="httpRequestHandler" /> 
  29.  </bean> 
  30.  <bean id="httpRequestHandler" class="org.jboss.netty.example.http.snoop.HttpRequestHandler" scope="prototype"> 
  31.     <property name="databaseUtil" ref="databaseUtil" /> 
  32.     <property name="redisUtil" ref="redisUtil" /> 
  33.  </bean> 

4.测试

访问

http://127.0.0.1:8081/sfds?username=yifangyou

 

 

 

源码下载:http://down.51cto.com/data/229434

 

修改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 RedisUtil redisUtil;  
  47.       private HttpRequest request;  
  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.               HttpRequest request = this.request = (HttpRequest) e.getMessage();  
  54.               redisUtil.setData("yifangyou""testpassword");  
  55.               buf.setLength(0);  
  56.               QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());  
  57.               Map<String, List<String>> params = queryStringDecoder.getParameters();       
  58.               if (!params.isEmpty()) {  
  59.                   HttpResponseStatus httpResponseStatus=HttpResponseStatus.OK;             
  60.                   if(params.containsKey("username")){  
  61.                       List<String> values=params.get("username");  
  62.                       String username="";  
  63.                       if(values.size()>0){  
  64.                           username=values.get(0);  
  65.                       }  
  66.                       String password=redisUtil.getData(username);  
  67.                       if(password==null){  
  68.                           buf.append("not found ");  
  69.                       }else{  
  70.                           buf.append(username+"'s password is:"+password);  
  71.                       }  
  72.                   }else{  
  73.                       buf.append("miss username");  
  74.                   }         
  75.                   writeResponse(e,httpResponseStatus,buf);  
  76.               }else{  
  77.                   buf.append("miss username");  
  78.                   writeResponse(e,OK,buf);  
  79.               }  
  80.      }  
  81.    
  82.      private void writeResponse(MessageEvent e,HttpResponseStatus httpResponseStatus,StringBuilder buf) {  
  83.          // Decide whether to close the connection or not.  
  84.          boolean keepAlive = isKeepAlive(request);  
  85.    
  86.          // Build the response object.  
  87.          HttpResponse response = new DefaultHttpResponse(HTTP_1_1, httpResponseStatus);  
  88.          response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));  
  89.          response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");  
  90.    
  91.          // Write the response.  
  92.          ChannelFuture future = e.getChannel().write(response);  
  93.    
  94.          // Close the non-keep-alive connection after the write operation is done.  
  95.          future.addListener(ChannelFutureListener.CLOSE);  
  96.      }  
  97.    
  98.      private void send100Continue(MessageEvent e) {  
  99.          HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);  
  100.          e.getChannel().write(response);  
  101.      }  
  102.    
  103.      @Override 
  104.      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)  
  105.              throws Exception {  
  106.          e.getCause().printStackTrace();  
  107.          e.getChannel().close();  
  108.      }  
  109.  
  110.     public void setDatabaseUtil(DatabaseUtil databaseUtil) {  
  111.         this.databaseUtil = databaseUtil;  
  112.     }  
  113.  
  114.     public DatabaseUtil getDatabaseUtil() {  
  115.         return databaseUtil;  
  116.     }  
  117.  
  118.     public void setRedisUtil(RedisUtil redisUtil) {  
  119.         this.redisUtil = redisUtil;  
  120.     }  
  121.  
  122.     public RedisUtil getRedisUtil() {  
  123.         return redisUtil;  
  124.     }  
  125.  }  

本文出自 “一方有” 博客,请务必保留此出处http://yifangyou.blog.51cto.com/900206/628163

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics