java获取redis中各种数据类型key对应的value代码简单封装

来源:http://blog.csdn.net/russ44/article/details/52121180

目前在做自动化测试时,设计到需要获取存储在redis中的值,总结了操作代码如下:

需要jar包:jedis-2.7.3.jar、commons-pool2-2.4.1.jar


 code如下:

  1. package cn.migu.utils;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5.   
  6. import cn.migu.base.GlobalSettings;  
  7. import redis.clients.jedis.Jedis;  
  8. import redis.clients.jedis.JedisPool;  
  9. import redis.clients.jedis.JedisPoolConfig;  
  10. /** 
  11.  * <Description>redis相关操作类 
  12.  * @author YanLu 
  13.  * 
  14.  */  
  15. public class RedisUtil {  
  16.     private JedisPool pool=null;  
  17.     private Jedis redis = null;  
  18.     Log4jUtil log = new Log4jUtil(this.getClass().getName());  
  19.     //构造函数,创建对象时进行初始化  
  20.     public RedisUtil() {  
  21.         if (pool == null) {  
  22.             /* 
  23.             // 池基本配置 
  24.             //JedisPoolConfig config = new JedisPoolConfig(); 
  25.             // 最大连接数, 默认8个 
  26.             config.setMaxTotal(20); 
  27.             // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。 
  28.             config.setMaxIdle(5); 
  29.             // 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException; 
  30.             config.setMaxWaitMillis(10000); 
  31.             // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; 
  32.             config.setTestOnBorrow(false); 
  33.             */  
  34.               
  35.             //创建redis连接池  
  36.             //this.pool = new JedisPool(config,"172.18.173.188",6379);  
  37.             this.pool = new JedisPool(new JedisPoolConfig(), GlobalSettings.getProperty("redis.master.host"), Integer.parseInt(GlobalSettings.getProperty("redis.master.port")));  
  38.             //获取Jedis实例  
  39.             this.redis = pool.getResource();  
  40.             log.info("Connection to redis server sucessfully");  
  41.         }  
  42.     }  
  43.       
  44.     /** 
  45.      * 关闭连接 
  46.      * @param pool 
  47.      * @param redis 
  48.      */  
  49.     public void quitConnection(Jedis redis) {  
  50.         if (redis != null) {  
  51.             redis.quit();  
  52.             //pool.returnResource(redis);  
  53.         }  
  54.     }  
  55.       
  56.     /** 
  57.      * 获取key对应的value 
  58.      *  
  59.      * 说明:方法中目前只针对key数据类型为String和hash的情况作了处理,其他数据类型可根据需要进行扩展即可 
  60.      * @param key 
  61.      * @return 
  62.      */  
  63.     public String getValue(String key){  
  64.         String value = null;  
  65.         try {  
  66.             if(redis == null || !redis.exists(key)){  
  67.                 log.info("key:"+key+" is not found");  
  68.                 quitConnection(redis);  
  69.                 return value;  
  70.             }  
  71.             //获取key对应的数据类型  
  72.             String type = redis.type(key);  
  73.             log.info("key:" + key + " 的类型为:" + type);  
  74.             if(type.equals("string")){  
  75.                 //get(key)方法返回key所关联的字符串值  
  76.                 value = redis.get(key);  
  77.             }  
  78.             if(type.equals("hash")){  
  79.                 //一下方法仅适用于list.size=1时,否者value将取集合中最后一个元素的值  
  80.                 List<String> list = redis.hvals(key);//hvals(key)返回哈希表 key 中所有域的值  
  81.                 //Set<String> set = redis.hkeys(key);  
  82.                 Iterator<String> it=list.iterator();  
  83.                 while(it.hasNext()){     
  84.                     value = it.next();  
  85.                     log.info("value:"+value);  
  86.                 }  
  87.             }  
  88.             if(type.equals("list")){  
  89.                 log.info(key+"类型为list暂未处理...");  
  90.             }  
  91.             if(type.equals("set")){  
  92.                 log.info(key+"类型为list暂未处理...");  
  93.             }  
  94.         } catch (Exception e) {  
  95.             // TODO Auto-generated catch block  
  96.             e.printStackTrace();  
  97.         }finally{  
  98.             //关闭连接  
  99.             quitConnection(redis);  
  100.         }  
  101.         return value;  
  102.     }  
  103.       
package cn.migu.utils;

import java.util.Iterator;
import java.util.List;

import cn.migu.base.GlobalSettings;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
 * <Description>redis相关操作类
 * @author YanLu
 *
 */
public class RedisUtil {
	private JedisPool pool=null;
	private Jedis redis = null;
	Log4jUtil log = new Log4jUtil(this.getClass().getName());
	//构造函数,创建对象时进行初始化
	public RedisUtil() {
		if (pool == null) {
			/*
			// 池基本配置
			//JedisPoolConfig config = new JedisPoolConfig();
			// 最大连接数, 默认8个
			config.setMaxTotal(20);
			// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
			config.setMaxIdle(5);
			// 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
			config.setMaxWaitMillis(10000);
			// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
			config.setTestOnBorrow(false);
			*/
			
			//创建redis连接池
			//this.pool = new JedisPool(config,"172.18.173.188",6379);
			this.pool = new JedisPool(new JedisPoolConfig(), GlobalSettings.getProperty("redis.master.host"), Integer.parseInt(GlobalSettings.getProperty("redis.master.port")));
			//获取Jedis实例
			this.redis = pool.getResource();
			log.info("Connection to redis server sucessfully");
		}
	}
	
	/**
	 * 关闭连接
	 * @param pool
	 * @param redis
	 */
	public void quitConnection(Jedis redis) {
		if (redis != null) {
			redis.quit();
			//pool.returnResource(redis);
		}
	}
	
	/**
	 * 获取key对应的value
	 * 
	 * 说明:方法中目前只针对key数据类型为String和hash的情况作了处理,其他数据类型可根据需要进行扩展即可
	 * @param key
	 * @return
	 */
	public String getValue(String key){
		String value = null;
		try {
			if(redis == null || !redis.exists(key)){
				log.info("key:"+key+" is not found");
				quitConnection(redis);
				return value;
			}
			//获取key对应的数据类型
			String type = redis.type(key);
			log.info("key:" + key + " 的类型为:" + type);
			if(type.equals("string")){
				//get(key)方法返回key所关联的字符串值
				value = redis.get(key);
			}
			if(type.equals("hash")){
				//一下方法仅适用于list.size=1时,否者value将取集合中最后一个元素的值
				List<String> list = redis.hvals(key);//hvals(key)返回哈希表 key 中所有域的值
				//Set<String> set = redis.hkeys(key);
				Iterator<String> it=list.iterator();
				while(it.hasNext()){   
			        value = it.next();
			        log.info("value:"+value);
				}
			}
			if(type.equals("list")){
				log.info(key+"类型为list暂未处理...");
			}
			if(type.equals("set")){
				log.info(key+"类型为list暂未处理...");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//关闭连接
			quitConnection(redis);
		}
		return value;
	}
	
  1. </pre><p></p><p></p><p>测试代码如下:</p><p><pre name="code" class="java">package cn.migu.test;  
  2.   
  3. import org.testng.annotations.Test;  
  4.   
  5. import cn.migu.utils.Log4jUtil;  
  6. import cn.migu.utils.RedisUtil;  
  7.   
  8. /** 
  9.  * <Description> 测试RedisUtil类 
  10.  * @author YanLu 
  11.  *  
  12.  */  
  13. public class TestRedis {  
  14.     private Log4jUtil log = new Log4jUtil(this.getClass().getName());  
  15.     @Test  
  16.     public void testRedisUtil(){  
  17.         RedisUtil ru = new RedisUtil();  
  18.         //获取redis中对应的value值  
  19.         String value=ru.getValue("SMS_NODE_TIMES_13814528620");  
  20.         log.info(value);      
  21.     }  
  22.     
  23. }  

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用和引用的内容,如果从共用的Redis获取的数据是乱码,可能有两个原因。首先,模块C的默认字符集是GB2312,而Java的字符集是UTF-8,两边的编码不一致导致乱码。其次,模块C的同事封装的dll库,向Redis的列表push的时候,不是push的字符串,而是byte数组。因此,你可以将Java代码的字符集设置为GB2312来保持一致,或者尝试使用其他字符集进行适配。 另外,根据引用的内容,你可以通过改变RedisTemplate的默认序列化方式来解决文乱码的问题。你可以将key的序列化方式改为StringRedisSerializer,将value的序列化方式改为Jackson2JsonRedisSerializer。你可以将以下代码放到Spring Boot的启动类: ``` @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); jackson2JsonRedisSerializer.setObjectMapper(new ObjectMapper()); RedisSerializer<String> stringSerializer = new StringRedisSerializer(); template.setKeySerializer(stringSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } ``` 通过以上改变,你应该能够解决Java代码Redis文乱码的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【Java】记一次通过Javaredis获取json数据文乱码问题的解决](https://blog.csdn.net/baidu_15338861/article/details/107859793)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [java存储redis数据类型以及客户端查看文乱码的问题解决](https://blog.csdn.net/lifulian318/article/details/126699509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值