java中使用Jedis操作Redis实例

要想在Java中连接Redis,并进行操作,由两种方式,一种是spring data redis,它是由spring集成的,不支持集群,一种是官方推荐的jedis,支持集群,其他功能差不多一样,

这里我们介绍jedis操作实例,以下是使用Jedis的具体步骤:

1、如果是在Maven项目中,在pom.xml中增加如下语句,如果不是Maven项目下载包导入项目即可:

[java]  view plain  copy
  1. <dependency>  
  2.             <groupId>redis.clients</groupId>  
  3.             <artifactId>jedis</artifactId>  
  4.             <version>2.6.2</version>  
  5.         </dependency>  

2、创建redis.properties配置文件,设置连接参数

[java]  view plain  copy
  1. # Redis settings    
  2. redis.host=192.168.0.240  
  3. redis.port=6379  
  4. redis.pass=xxxxxx  
  5. redis.timeout=10000  
  6.   
  7. redis.maxIdle=300  
  8. redis.maxTotal=600  
  9. # 毫秒  
  10. redis.maxWaitMillis=1000  
  11. redis.testOnBorrow=false  

3、创建属性文件加载工具类,用于获取redis.properties文件

[java]  view plain  copy
  1. package com.rmd.cart.utils;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6.   
  7. /** 
  8.  * 属性文件加载工具类 
  9.  * @author lc 
  10.  */  
  11. public class PropertyUtil {  
  12.      
  13.     //加载property文件到io流里面  
  14.     public static Properties loadProperties(String propertyFile) {  
  15.         Properties properties = new Properties();  
  16.         try {  
  17.             InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);  
  18.             if(is == null){  
  19.                 is = PropertyUtil.class.getClassLoader().getResourceAsStream("properties/" + propertyFile);  
  20.             }  
  21.             properties.load(is);  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.         return properties;  
  26.     }  
  27.   
  28.     /** 
  29.      * 根据key值取得对应的value值 
  30.      * 
  31.      * @param key 
  32.      * @return 
  33.      */  
  34.     public static String getValue(String propertyFile, String key) {  
  35.         Properties properties = loadProperties(propertyFile);  
  36.         return properties.getProperty(key);  
  37.     }  
  38. }  

4、创建连接redis工具类

[java]  view plain  copy
  1. package com.rmd.cart.utils;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5. import java.util.Properties;  
  6. import java.util.Set;  
  7.   
  8. import redis.clients.jedis.Jedis;  
  9. import redis.clients.jedis.JedisPool;  
  10. import redis.clients.jedis.JedisPoolConfig;  
  11.   
  12. /** 
  13.  * redis工具类 
  14.  * @author lc 
  15.  */  
  16. public class JedisUtil {  
  17.     private static JedisPool jedisPool = null;  
  18.   
  19.     private JedisUtil() {  
  20.   
  21.     }  
  22.       
  23.     //写成静态代码块形式,只加载一次,节省资源  
  24.     static {  
  25.         Properties properties = PropertyUtil.loadProperties("redis.properties");  
  26.         String host = properties.getProperty("redis.host");  
  27.         String port = properties.getProperty("redis.port");  
  28.         String pass = properties.getProperty("redis.pass");  
  29.         String timeout = properties.getProperty("redis.timeout");  
  30.         String maxIdle = properties.getProperty("redis.maxIdle");  
  31.         String maxTotal = properties.getProperty("redis.maxTotal");  
  32.         String maxWaitMillis = properties.getProperty("redis.maxWaitMillis");  
  33.         String testOnBorrow = properties.getProperty("redis.testOnBorrow");  
  34.   
  35.         JedisPoolConfig config = new JedisPoolConfig();  
  36.         //控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;  
  37.         //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。  
  38.         config.setMaxTotal(Integer.parseInt(maxTotal));  
  39.         //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。  
  40.         config.setMaxIdle(Integer.parseInt(maxIdle));  
  41.         //表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;  
  42.         config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));  
  43.         //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;  
  44.         config.setTestOnBorrow(Boolean.valueOf(testOnBorrow));  
  45.   
  46.         jedisPool = new JedisPool(config, host, Integer.parseInt(port), Integer.parseInt(timeout), pass);  
  47.     }  
  48.   
  49.     /** 
  50.      * 从jedis连接池中获取获取jedis对象 
  51.      * 
  52.      * @return 
  53.      */  
  54.     private Jedis getJedis() {  
  55.         return jedisPool.getResource();  
  56.     }  
  57.   
  58.     private static final JedisUtil jedisUtil = new JedisUtil();  
  59.   
  60.     /** 
  61.      * 获取JedisUtil实例 
  62.      * 
  63.      * @return 
  64.      */  
  65.     public static JedisUtil getInstance() {  
  66.         return jedisUtil;  
  67.     }  
  68.   
  69.     /** 
  70.      * 回收jedis(放到finally中) 
  71.      * 
  72.      * @param jedis 
  73.      */  
  74.     private void returnJedis(Jedis jedis) {  
  75.         if (null != jedis && null != jedisPool) {  
  76.             jedisPool.returnResource(jedis);  
  77.         }  
  78.     }  
  79.   
  80.     /** 
  81.      * 销毁连接(放到catch中) 
  82.      * 
  83.      * @param jedis 
  84.      */  
  85.     private static void returnBrokenResource(Jedis jedis) {  
  86.         if (null != jedis && null != jedisPool) {  
  87.             jedisPool.returnResource(jedis);  
  88.         }  
  89.     }  
  90.   
  91.     /** 
  92.      * 添加sorted set 
  93.      * 
  94.      * @param key 
  95.      * @param value 
  96.      * @param score 
  97.      */  
  98.     public void zadd(String key, String value, double score) {  
  99.         Jedis jedis = getJedis();  
  100.         jedis.zadd(key, score, value);  
  101.         returnJedis(jedis);  
  102.     }  
  103.   
  104.     /** 
  105.      * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素 
  106.      * @param key 
  107.      * @param start 
  108.      * @param end 
  109.      * @return 
  110.      */  
  111.     public Set<String> zrange(String key, int start, int end) {  
  112.         Jedis jedis = getJedis();  
  113.         Set<String> set = jedis.zrange(key, start, end);  
  114.         returnJedis(jedis);  
  115.         return set;  
  116.     }  
  117.   
  118.     /** 
  119.      * 获取给定区间的元素,原始按照权重由高到低排序 
  120.      * @param key 
  121.      * @param start 
  122.      * @param end 
  123.      * @return 
  124.      */  
  125.     public Set<String> zrevrange(String key, int start, int end) {  
  126.         Jedis jedis = getJedis();  
  127.         Set<String> set = jedis.zrevrange(key, start, end);  
  128.         returnJedis(jedis);  
  129.         return set;  
  130.     }  
  131.   
  132.     /** 
  133.      * 添加对应关系,如果对应关系已存在,则覆盖 
  134.      * 
  135.      * @param key 
  136.      * @param map 对应关系 
  137.      * @return 状态,成功返回OK 
  138.      */  
  139.     public String hmset(String key, Map<String, String> map) {  
  140.         Jedis jedis = getJedis();  
  141.         String s = jedis.hmset(key, map);  
  142.         returnJedis(jedis);  
  143.         return s;  
  144.     }  
  145.   
  146.     /** 
  147.      * 向List头部追加记录 
  148.      * 
  149.      * @param key 
  150.      * @param value 
  151.      * @return 记录总数 
  152.      */  
  153.     public long rpush(String key, String value) {  
  154.         Jedis jedis = getJedis();  
  155.         long count = jedis.rpush(key, value);  
  156.         returnJedis(jedis);  
  157.         return count;  
  158.     }  
  159.   
  160.     /** 
  161.      * 向List头部追加记录 
  162.      * 
  163.      * @param key 
  164.      * @param value 
  165.      * @return 记录总数 
  166.      */  
  167.     private long rpush(byte[] key, byte[] value) {  
  168.         Jedis jedis = getJedis();  
  169.         long count = jedis.rpush(key, value);  
  170.         returnJedis(jedis);  
  171.         return count;  
  172.     }  
  173.   
  174.     /** 
  175.      * 删除 
  176.      * 
  177.      * @param key 
  178.      * @return 
  179.      */  
  180.     public long del(String key) {  
  181.         Jedis jedis = getJedis();  
  182.         long s = jedis.del(key);  
  183.         returnJedis(jedis);  
  184.         return s;  
  185.     }  
  186.   
  187.     /** 
  188.      * 从集合中删除成员 
  189.      * @param key 
  190.      * @param value 
  191.      * @return 返回1成功 
  192.      * */  
  193.     public long zrem(String key, String... value) {  
  194.         Jedis jedis = getJedis();  
  195.         long s = jedis.zrem(key, value);  
  196.         returnJedis(jedis);  
  197.         return s;  
  198.     }  
  199.       
  200.     public void saveValueByKey(int dbIndex, byte[] key, byte[] value, int expireTime)  
  201.             throws Exception {  
  202.         Jedis jedis = null;  
  203.         boolean isBroken = false;  
  204.         try {  
  205.             jedis = getJedis();  
  206.             jedis.select(dbIndex);  
  207.             jedis.set(key, value);  
  208.             if (expireTime > 0)  
  209.                 jedis.expire(key, expireTime);  
  210.         } catch (Exception e) {  
  211.             isBroken = true;  
  212.             throw e;  
  213.         } finally {  
  214.             returnResource(jedis, isBroken);  
  215.         }  
  216.     }  
  217.       
  218.     public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {  
  219.         Jedis jedis = null;  
  220.         byte[] result = null;  
  221.         boolean isBroken = false;  
  222.         try {  
  223.             jedis = getJedis();  
  224.             jedis.select(dbIndex);  
  225.             result = jedis.get(key);  
  226.         } catch (Exception e) {  
  227.             isBroken = true;  
  228.             throw e;  
  229.         } finally {  
  230.             returnResource(jedis, isBroken);  
  231.         }  
  232.         return result;  
  233.     }  
  234.       
  235.     public void deleteByKey(int dbIndex, byte[] key) throws Exception {  
  236.         Jedis jedis = null;  
  237.         boolean isBroken = false;  
  238.         try {  
  239.             jedis = getJedis();  
  240.             jedis.select(dbIndex);  
  241.             jedis.del(key);  
  242.         } catch (Exception e) {  
  243.             isBroken = true;  
  244.             throw e;  
  245.         } finally {  
  246.             returnResource(jedis, isBroken);  
  247.         }  
  248.     }  
  249.       
  250.     public void returnResource(Jedis jedis, boolean isBroken) {  
  251.         if (jedis == null)  
  252.             return;  
  253.         if (isBroken)  
  254.             jedisPool.returnBrokenResource(jedis);  
  255.         else  
  256.             jedisPool.returnResource(jedis);  
  257.     }  
  258.       
  259.     /** 
  260.      * 获取总数量 
  261.      * @param key 
  262.      * @return 
  263.      */  
  264.     public long zcard(String key) {  
  265.         Jedis jedis = getJedis();  
  266.         long count = jedis.zcard(key);  
  267.         returnJedis(jedis);  
  268.         return count;  
  269.     }  
  270.   
  271.     /** 
  272.      * 是否存在KEY 
  273.      * @param key 
  274.      * @return 
  275.      */  
  276.     public boolean exists(String key) {  
  277.         Jedis jedis = getJedis();  
  278.         boolean exists = jedis.exists(key);  
  279.         returnJedis(jedis);  
  280.         return exists;  
  281.     }  
  282.   
  283.     /** 
  284.      * 重命名KEY 
  285.      * @param oldKey 
  286.      * @param newKey 
  287.      * @return 
  288.      */  
  289.     public String rename(String oldKey, String newKey) {  
  290.         Jedis jedis = getJedis();  
  291.         String result = jedis.rename(oldKey, newKey);  
  292.         returnJedis(jedis);  
  293.         return result;  
  294.     }  
  295.   
  296.     /** 
  297.      * 设置失效时间 
  298.      * @param key 
  299.      * @param seconds 
  300.      */  
  301.     public void expire(String key, int seconds) {  
  302.         Jedis jedis = getJedis();  
  303.         jedis.expire(key, seconds);  
  304.         returnJedis(jedis);  
  305.     }  
  306.   
  307.     /** 
  308.      * 删除失效时间 
  309.      * @param key 
  310.      */  
  311.     public void persist(String key) {  
  312.         Jedis jedis = getJedis();  
  313.         jedis.persist(key);  
  314.         returnJedis(jedis);  
  315.     }  
  316.       
  317.     /** 
  318.      * 添加一个键值对,如果键存在不在添加,如果不存在,添加完成以后设置键的有效期 
  319.      * @param key 
  320.      * @param value 
  321.      * @param timeOut 
  322.      */  
  323.     public void setnxWithTimeOut(String key,String value,int timeOut){  
  324.         Jedis jedis = getJedis();  
  325.         if(0!=jedis.setnx(key, value)){  
  326.             jedis.expire(key, timeOut);  
  327.         }  
  328.         returnJedis(jedis);  
  329.     }  
  330.       
  331.     /** 
  332.      * 返回指定key序列值  
  333.      * @param key 
  334.      * @return 
  335.      */  
  336.     public long incr(String key){  
  337.         Jedis jedis = getJedis();  
  338.         long l = jedis.incr(key);  
  339.         returnJedis(jedis);  
  340.         return l;  
  341.     }  
  342.       
  343.     /** 
  344.      * 获取当前时间  
  345.      * @return 秒 
  346.      */  
  347.     public long currentTimeSecond(){  
  348.         Long l = 0l;  
  349.         Jedis jedis = getJedis();  
  350.         Object obj = jedis.eval("return redis.call('TIME')",0);  
  351.         if(obj != null){  
  352.             List<String> list = (List)obj;  
  353.             l = Long.valueOf(list.get(0));  
  354.         }  
  355.         returnJedis(jedis);  
  356.         return l;  
  357.     }  
  358. }  

5、编写redis服务类

[java]  view plain  copy
  1. package com.rmd.cart.service.impl;  
  2. import java.util.Date;  
  3. import java.util.Set;  
  4. import org.springframework.stereotype.Service;  
  5. import com.rmd.cart.utils.JedisUtil;  
  6.   
  7. /** 
  8.  * redis服务 
  9.  * @author lc 
  10.  */  
  11. @Service("redisService")  
  12. public class RedisService {  
  13.   
  14.     /** 
  15.      * 添加SortSet型数据 
  16.      * @param key 
  17.      * @param value 
  18.      */  
  19.     public void addSortSet(String key, String value) {  
  20.         double score = new Date().getTime();  
  21.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  22.         jedisUtil.zadd(key, value, score);  
  23.     }  
  24.   
  25.     /** 
  26.      * 获取倒序的SortSet型的数据 
  27.      * @param key 
  28.      * @return 
  29.      */  
  30.     public Set<String> getDescSortSet(String key) {  
  31.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  32.         return jedisUtil.zrevrange(key, 0, -1);  
  33.     }  
  34.   
  35.     /** 
  36.      * 删除SortSet型数据 
  37.      * @param key 
  38.      * @param value 
  39.      */  
  40.     public void deleteSortSet(String key, String value) {  
  41.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  42.         jedisUtil.zrem(key, value);  
  43.     }  
  44.   
  45.     /** 
  46.      * 批量删除SortSet型数据 
  47.      * @param key 
  48.      * @param value 
  49.      */  
  50.     public void deleteSortSetBatch(String key, String[] value) {  
  51.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  52.         jedisUtil.zrem(key, value);  
  53.     }  
  54.       
  55.     /** 
  56.      * 范围获取倒序的SortSet型的数据 
  57.      * @param key 
  58.      * @return 
  59.      */  
  60.     public Set<String> getDescSortSetPage(String key,int start, int end) {  
  61.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  62.         return jedisUtil.zrevrange(key, start, end);  
  63.     }  
  64.   
  65.     /** 
  66.      * 获取SortSet型的总数量 
  67.      * @param key 
  68.      * @return 
  69.      */  
  70.     public long getSortSetAllCount(String key) {  
  71.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  72.         return jedisUtil.zcard(key);  
  73.     }  
  74.   
  75.     /** 
  76.      * 检查KEY是否存在 
  77.      * @param key 
  78.      * @return 
  79.      */  
  80.     public boolean checkExistsKey(String key) {  
  81.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  82.         return jedisUtil.exists(key);  
  83.     }  
  84.   
  85.     /** 
  86.      * 重命名KEY 
  87.      * @param oldKey 
  88.      * @param newKey 
  89.      * @return 
  90.      */  
  91.     public String renameKey(String oldKey, String newKey) {  
  92.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  93.         return jedisUtil.rename(oldKey, newKey);  
  94.     }  
  95.   
  96.     /** 
  97.      * 删除KEY 
  98.      * @param key 
  99.      */  
  100.     public void deleteKey(String key) {  
  101.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  102.         jedisUtil.del(key);  
  103.     }  
  104.   
  105.     /** 
  106.      * 设置失效时间 
  107.      * @param key 
  108.      * @param seconds 失效时间,秒 
  109.      */  
  110.     public void setExpireTime(String key, int seconds) {  
  111.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  112.         jedisUtil.expire(key, seconds);  
  113.     }  
  114.   
  115.     /** 
  116.      * 删除失效时间 
  117.      * @param key 
  118.      */  
  119.     public void deleteExpireTime(String key) {  
  120.         JedisUtil jedisUtil = JedisUtil.getInstance();  
  121.         jedisUtil.persist(key);  
  122.     }  
  123. }  
注意:以上是公共基础,下面是我业务操作,怎样保存数据和获取数据


6、由于我想做购物车,创建购物车service接口,代码如下

[java]  view plain  copy
  1. package com.rmd.cart.service;  
  2.   
  3. import java.util.Set;  
  4.   
  5.   
  6. /** 
  7.  * @Description: 购物车service 
  8.  * @author lc 
  9.  */  
  10. public interface CartService {  
  11.       
  12.     /** 
  13.      *  
  14.      * @Description: 添加购物车 
  15.      * @author lc 
  16.      * @param customerId 
  17.      * void 
  18.      */  
  19.     public void add(String customerId);  
  20.       
  21.     /** 
  22.      * @Description: 获取购物车数据 
  23.      * @author lc 
  24.      * @param customerId 
  25.      * @return 
  26.      * Set<String> 
  27.      */  
  28.     public Set<String> getCart(String customerId);  
  29.   
  30. }  

7、创建impl类实现service接口,代码如下

[java]  view plain  copy
  1. package com.rmd.cart.service.impl;  
  2.   
  3. import java.util.Set;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Service;  
  7.   
  8. import com.rmd.cart.service.CartService;  
  9.   
  10. @Service("cartService")  
  11. public class CartServiceImpl implements CartService {  
  12.       
  13.     @Autowired  
  14.     private RedisService redisService;  
  15.   
  16.     @Override  
  17.     public void add(String customerId) {  
  18.         redisService.addSortSet("rmd_cart_test123", customerId);  
  19.     }  
  20.   
  21.     @Override  
  22.     public Set<String> getCart(String customerId) {  
  23.         return redisService.getDescSortSet("rmd_cart_test123");  
  24.     }  
  25.   
  26. }  

8、创建一个对象类,用户数据测试

[java]  view plain  copy
  1. package com.rmd.cart.bean;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. public class SpuInfo implements Serializable{  
  7.       
  8.     private Integer spuid;//spuid  
  9.     private long createTime;//添加时间  
  10.     private List<SkuInfo> skuList;//sku信息集合  
  11.       
  12.     public Integer getSpuid() {  
  13.         return spuid;  
  14.     }  
  15.     public void setSpuid(Integer spuid) {  
  16.         this.spuid = spuid;  
  17.     }  
  18.     public long getCreateTime() {  
  19.         return createTime;  
  20.     }  
  21.     public void setCreateTime(long createTime) {  
  22.         this.createTime = createTime;  
  23.     }  
  24.     public List<SkuInfo> getSkuList() {  
  25.         return skuList;  
  26.     }  
  27.     public void setSkuList(List<SkuInfo> skuList) {  
  28.         this.skuList = skuList;  
  29.     }  
  30. }  

9、创建测试类,使用junit4进行测试

添加数据

[java]  view plain  copy
  1. package rmd_cart_provider.service.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringWriter;  
  5. import java.io.Writer;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.codehaus.jackson.JsonGenerationException;  
  10. import org.codehaus.jackson.map.JsonMappingException;  
  11. import org.codehaus.jackson.map.ObjectMapper;  
  12. import org.junit.Test;  
  13. import org.junit.runner.RunWith;  
  14. import org.springframework.test.context.ContextConfiguration;  
  15. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  16.   
  17. import com.rmd.cart.bean.SpuInfo;  
  18. import com.rmd.cart.service.CartService;  
  19.   
  20. @RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试  
  21. @ContextConfiguration({"/applicationContext.xml"}) //加载配置文件  
  22. public class CartTest {  
  23.   
  24.   
  25.     @Resource    
  26.     private CartService cartService;  
  27.   
  28.     @Test     
  29.     public void test() throws JsonGenerationException, JsonMappingException, IOException{  
  30.           
  31.         SpuInfo spu = new SpuInfo();  
  32.         spu.setSpuid(123);  
  33.         spu.setCreateTime(105456464);  
  34.           
  35.         //将对象转换成json字符串  
  36.         ObjectMapper om = new ObjectMapper();  
  37.         Writer wr = new StringWriter();  
  38.         om.writeValue(wr, spu);  
  39.           
  40.         String str = wr.toString();  
  41.         //添加数据  
  42.         cartService.add(str);  
  43.           
  44.     }  
  45. }  

获取数据

[java]  view plain  copy
  1. package rmd_cart_provider.service.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7. import java.util.Set;  
  8.   
  9. import javax.annotation.Resource;  
  10.   
  11. import org.codehaus.jackson.JsonGenerationException;  
  12. import org.codehaus.jackson.map.JsonMappingException;  
  13. import org.codehaus.jackson.map.ObjectMapper;  
  14. import org.junit.Test;  
  15. import org.junit.runner.RunWith;  
  16. import org.springframework.test.context.ContextConfiguration;  
  17. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  18.   
  19. import com.rmd.cart.bean.SpuInfo;  
  20. import com.rmd.cart.service.CartService;  
  21.   
  22. @RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试  
  23. @ContextConfiguration({"/applicationContext.xml"}) //加载配置文件  
  24. public class CartTest {  
  25.   
  26.   
  27.     @Resource    
  28.     private CartService cartService;  
  29.   
  30.     @Test     
  31.     public void test() throws JsonGenerationException, JsonMappingException, IOException{  
  32.         //获取数据  
  33.         List<SpuInfo> spuList = new ArrayList<>();  
  34.         ObjectMapper om = new ObjectMapper();  
  35.          //转回对象  
  36.         Set<String> set = cartService.getCart(null);  
  37.           
  38.         Iterator<String> iterator = set.iterator();  
  39.         while (iterator.hasNext()) {  
  40.             String value = iterator.next();  
  41.             SpuInfo spuVo = om.readValue(value, SpuInfo.class);  
  42.             spuList.add(spuVo);  
  43.         }  
  44.           
  45.     }  
  46. }  

上面添加和获取数据的时候用到了JUnit4和ObjectMapper

JUnit4单元测试,这个应该都知道,只要加入包就行

[java]  view plain  copy
  1.        <dependency>  
  2.      <groupId>junit</groupId>  
  3.      <artifactId>junit</artifactId>  
  4.      <version>4.12</version>  
  5.      <scope>test</scope>  
  6. </dependency>  
  7. <dependency>  
  8.     <groupId>org.springframework</groupId>  
  9.     <artifactId>spring-test</artifactId>  
  10.     <version>${spring.version}</version>  
  11. </dependency>  
  12. <dependency>  
  13.     <groupId>org.springframework</groupId>  
  14.     <artifactId>spring-tx</artifactId>  
  15.     <version>${spring.version}</version>  
  16. </dependency>  

ObjectMapper这个是一个高效的对象和json之间转换的类,具体方法查文档,谁用都说好,推荐给大家

[java]  view plain  copy
  1. <dependency>  
  2.          <groupId>org.codehaus.jackson</groupId>  
  3.          <artifactId>jackson-mapper-asl</artifactId>  
  4.          <version>1.9.4</version>  
  5.         </dependency>  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值