netty里集成spring注入jedis

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介:

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.  


  1.     public DatabaseUtil getDatabaseUtil() {  
  2.         return databaseUtil;  
  3.     }  
  4.  
  5.     public void setRedisUtil(RedisUtil redisUtil) {  
  6.         this.redisUtil = redisUtil;  
  7.     }  
  8.  
  9.     public RedisUtil getRedisUtil() {  
  10.         return redisUtil;  
  11.     }  
  12.  }  


本文转自yifangyou 51CTO博客,原文链接:http://blog.51cto.com/yifangyou/628163 ,如需转载请自行联系原作者


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
3天前
|
Java Maven Docker
gitlab-ci 集成 k3s 部署spring boot 应用
gitlab-ci 集成 k3s 部署spring boot 应用
|
2月前
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
定时任务在企业应用中至关重要,常用于异步数据处理、自动化运维等场景。在单体应用中,利用Java的`java.util.Timer`或Spring的`@Scheduled`即可轻松实现。然而,进入微服务架构后,任务可能因多节点并发执行而重复。Spring Cloud Alibaba为此发布了Scheduling模块,提供轻量级、高可用的分布式定时任务解决方案,支持防重复执行、分片运行等功能,并可通过`spring-cloud-starter-alibaba-schedulerx`快速集成。用户可选择基于阿里云SchedulerX托管服务或采用本地开源方案(如ShedLock)
|
1天前
|
NoSQL Java Redis
redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。
这篇文章介绍了Redis的基本命令,并展示了如何使用Netty框架直接与Redis服务器进行通信,包括设置Netty客户端、编写处理程序以及初始化Channel的完整示例代码。
9 1
redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。
|
10天前
|
存储 前端开发 Java
Spring Boot 集成 MinIO 与 KKFile 实现文件预览功能
本文详细介绍如何在Spring Boot项目中集成MinIO对象存储系统与KKFileView文件预览工具,实现文件上传及在线预览功能。首先搭建MinIO服务器,并在Spring Boot中配置MinIO SDK进行文件管理;接着通过KKFileView提供文件预览服务,最终实现文档管理系统的高效文件处理能力。
|
17天前
|
NoSQL 网络协议 Java
[Redis] 渐进式遍历+使用jedis操作Redis+使用Spring操作Redis
[Redis] 渐进式遍历+使用jedis操作Redis+使用Spring操作Redis
28 7
|
18天前
|
NoSQL Java 网络安全
[Redis] 渐进式遍历+使用jedis操作Redis+使用Spring操作Redis
[Redis] 渐进式遍历+使用jedis操作Redis+使用Spring操作Redis
|
2月前
|
XML Java 数据格式
Spring5入门到实战------4、IOC容器-Bean管理XML方式、集合的注入(二)
这篇文章是Spring5框架的实战教程,主题是IOC容器中Bean的集合属性注入,通过XML配置方式。文章详细讲解了如何在Spring中注入数组、List、Map和Set类型的集合属性,并提供了相应的XML配置示例和Java类定义。此外,还介绍了如何在集合中注入对象类型值,以及如何使用Spring的util命名空间来实现集合的复用。最后,通过测试代码和结果展示了注入效果。
Spring5入门到实战------4、IOC容器-Bean管理XML方式、集合的注入(二)
|
2月前
|
测试技术 Java Spring
Spring 框架中的测试之道:揭秘单元测试与集成测试的双重保障,你的应用真的安全了吗?
【8月更文挑战第31天】本文以问答形式深入探讨了Spring框架中的测试策略,包括单元测试与集成测试的有效编写方法,及其对提升代码质量和可靠性的重要性。通过具体示例,展示了如何使用`@MockBean`、`@SpringBootTest`等注解来进行服务和控制器的测试,同时介绍了Spring Boot提供的测试工具,如`@DataJpaTest`,以简化数据库测试流程。合理运用这些测试策略和工具,将助力开发者构建更为稳健的软件系统。
40 0
|
2月前
|
数据库 开发者 Java
颠覆传统开发:Hibernate与Spring Boot的集成,让你的开发效率飞跃式提升!
【8月更文挑战第31天】在 Java 开发中,Spring Boot 和 Hibernate 已成为许多开发者的首选技术栈。Spring Boot 简化了配置和部署过程,而 Hibernate 则是一个强大的 ORM 框架,用于管理数据库交互。将两者结合使用,可以极大提升开发效率并构建高性能的现代 Java 应用。本文将通过代码示例展示如何在 Spring Boot 项目中集成 Hibernate,并实现基本的数据库操作,包括添加依赖、配置数据源、创建实体类和仓库接口,以及在服务层和控制器中处理 HTTP 请求。这种组合不仅简化了配置,还提供了一套强大的工具来快速开发现代 Java 应用程序。
75 0
|
2月前
|
消息中间件 安全 Java
Spring Boot 基于 SCRAM 认证集成 Kafka 的详解
【8月更文挑战第4天】本文详解Spring Boot结合SCRAM认证集成Kafka的过程。SCRAM为Kafka提供安全身份验证。首先确认Kafka服务已启用SCRAM,并准备认证凭据。接着,在`pom.xml`添加`spring-kafka`依赖,并在`application.properties`中配置Kafka属性,包括SASL_SSL协议与SCRAM-SHA-256机制。创建生产者与消费者类以实现消息的发送与接收功能。最后,通过实际消息传递测试集成效果与认证机制的有效性。