实战SSM_O2O商铺_45【Redis缓存】配置Redis在Service层加入缓存
文章目錄
- 概述
- Windows下安裝Redis
- O2O-Service層加入緩存的配置步驟
- 1. pom.xml 添加jedis依賴包
- 2. redis配置文件
- 3.spring-dao.xml加載redis.properties
- 4.封裝JedisPool,用于創建JedisPool
- 5.封裝操作redis的工具類 JedisUtil
- 6.新建spring-redis.xml 配置redis連接池和bean
- 7. web.xml中加載spring-redis.xml
- 8.Service層使用緩存
- 9.單元測試
- 9.1 BaseTest基類中加載 classpath:spring-redis.xml
- 9.2 debug調測
- 10 Redis中驗證數據
- Github地址
概述
Redis 是一個高性能的key-value數據庫。
Redis性能十分優越,可以支持每秒十幾萬次的讀/寫操作,其性能遠超數據庫,并且支持集群、分布式、主從同步等配置,原則上可以無限擴展,讓更多的數據存儲在內存中,它還能支持一定的事務能力,這在高并發訪問的場景下保證數據安全和一致性特別有用。
Windows下安裝Redis
我這里的是windows的操作系統,下載地址:
https://github.com/ServiceStack/redis-windows/tree/master/downloads
下載最新版本
解壓即可,為了方便啟動,在解壓后的目錄下新建一個文件 startup.cmd,內容如下
redis-server redis.windows.conf該命令是調用 redis-server.exe 的命令讀取 redis.window.conf 的內容,用來啟動 redis,后面雙擊startup.cmd就可以看到 如下Redis 啟動的信息了.
可以雙擊放在同一個文件夾下的文件redis -cli .exe ,它是一個 Redis 自帶的客戶端工具,這樣就可以連接到 Redis 服務器. 通常我們使用第三方的客戶端,比如RedisDesktopManager
O2O-Service層加入緩存的配置步驟
1. pom.xml 添加jedis依賴包
在 Java 中使用 Redis 工具 , 要先下載 jedis.Jar 包,把它加載到工程的路徑中,首先去maven倉庫中查找 http://mvnrepository.com/artifact/redis.clients/jedis
<!-- redis客戶端:Jedis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency>我們沒有使用Spring提供的RedisTemplate 所以 這里沒有添加spring-data-redis.jar
2. redis配置文件
redis.hostname=127.0.0.1 redis.port=6379 redis.database=0 redis.pool.maxActive=600 redis.pool.maxIdle=300 redis.pool.maxWait=3000 redis.pool.testOnBorrow=true3.spring-dao.xml加載redis.properties
<bean class="com.artisan.o2o.util.EncryptPropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:jdbc.properties</value><value>classpath:redis.properties</value></list></property><property name="fileEncoding" value="UTF-8"/></bean>4.封裝JedisPool,用于創建JedisPool
package com.artisan.o2o.cache;import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig;/*** * * @ClassName: JedisPoolWriper* * @Description: 強指定redis的JedisPool接口構造函數,創建jedispool* * @author: Mr.Yang* * @date: 2018年8月10日 上午10:45:51*/ public class JedisPoolWriper {private JedisPool jedisPool;/*** * * @Title:JedisPoolWriper* * @Description:構造函數* * @param poolConfig* @param host* @param port*/public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host,final int port) {try {jedisPool = new JedisPool(poolConfig, host, port);} catch (Exception e) {e.printStackTrace();}}public JedisPool getJedisPool() {return jedisPool;}public void setJedisPool(JedisPool jedisPool) {this.jedisPool = jedisPool;}}5.封裝操作redis的工具類 JedisUtil
package com.artisan.o2o.cache;import java.util.List; import java.util.Map; import java.util.Set;import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.SortingParams; import redis.clients.util.SafeEncoder;public class JedisUtil {/*** 緩存生存時間*/private final int expire = 60000;/** 操作Key的方法 */public Keys KEYS;/** 對存儲結構為String類型的操作 */public Strings STRINGS;/** 對存儲結構為List類型的操作 */public Lists LISTS;/** 對存儲結構為Set類型的操作 */public Sets SETS;/** 對存儲結構為HashMap類型的操作 */public Hash HASH;private JedisPool jedisPool;public JedisPool getJedisPool() {return jedisPool;}public void setJedisPool(JedisPoolWriper jedisPoolWriper) {this.jedisPool = jedisPoolWriper.getJedisPool();}public JedisPool getPool() {return jedisPool;}/*** 從jedis連接池中獲取獲取jedis對象* * @return*/public Jedis getJedis() {return jedisPool.getResource();}/*** 設置過期時間* * @param key* @param seconds*/public void expire(String key, int seconds) {if (seconds <= 0) {return;}Jedis jedis = getJedis();jedis.expire(key, seconds);jedis.close();}/*** 設置默認過期時間* * @param key*/public void expire(String key) {expire(key, expire);}// *******************************************Keys*******************************************//public class Keys {/*** 清空所有key*/public String flushAll() {Jedis jedis = getJedis();String stata = jedis.flushAll();jedis.close();return stata;}/*** 更改key* * @param String* oldkey* @param String* newkey* @return 狀態碼* */public String rename(String oldkey, String newkey) {return rename(SafeEncoder.encode(oldkey),SafeEncoder.encode(newkey));}/*** 更改key,僅當新key不存在時才執行* * @param String* oldkey* @param String* newkey* @return 狀態碼* */public long renamenx(String oldkey, String newkey) {Jedis jedis = getJedis();long status = jedis.renamenx(oldkey, newkey);jedis.close();return status;}/*** 更改key* * @param String* oldkey* @param String* newkey* @return 狀態碼* */public String rename(byte[] oldkey, byte[] newkey) {Jedis jedis = getJedis();String status = jedis.rename(oldkey, newkey);jedis.close();return status;}/*** 設置key的過期時間,以秒為單位* * @param String* key* @param 時間* ,已秒為單位* @return 影響的記錄數* */public long expired(String key, int seconds) {Jedis jedis = getJedis();long count = jedis.expire(key, seconds);jedis.close();return count;}/*** 設置key的過期時間,它是距歷元(即格林威治標準時間 1970 年 1 月 1 日的 00:00:00,格里高利歷)的偏移量。* * @param String* key* @param 時間* ,已秒為單位* @return 影響的記錄數* */public long expireAt(String key, long timestamp) {Jedis jedis = getJedis();long count = jedis.expireAt(key, timestamp);jedis.close();return count;}/*** 查詢key的過期時間* * @param String* key* @return 以秒為單位的時間表示* */public long ttl(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();long len = sjedis.ttl(key);sjedis.close();return len;}/*** 取消對key過期時間的設置* * @param key* @return 影響的記錄數* */public long persist(String key) {Jedis jedis = getJedis();long count = jedis.persist(key);jedis.close();return count;}/*** 刪除keys對應的記錄,可以是多個key* * @param String* ... keys* @return 刪除的記錄數* */public long del(String... keys) {Jedis jedis = getJedis();long count = jedis.del(keys);jedis.close();return count;}/*** 刪除keys對應的記錄,可以是多個key* * @param String* ... keys* @return 刪除的記錄數* */public long del(byte[]... keys) {Jedis jedis = getJedis();long count = jedis.del(keys);jedis.close();return count;}/*** 判斷key是否存在* * @param String* key* @return boolean* */public boolean exists(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();boolean exis = sjedis.exists(key);sjedis.close();return exis;}/*** 對List,Set,SortSet進行排序,如果集合數據較大應避免使用這個方法* * @param String* key* @return List<String> 集合的全部記錄* **/public List<String> sort(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<String> list = sjedis.sort(key);sjedis.close();return list;}/*** 對List,Set,SortSet進行排序或limit* * @param String* key* @param SortingParams* parame 定義排序類型或limit的起止位置.* @return List<String> 全部或部分記錄* **/public List<String> sort(String key, SortingParams parame) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<String> list = sjedis.sort(key, parame);sjedis.close();return list;}/*** 返回指定key存儲的類型* * @param String* key* @return String string|list|set|zset|hash* **/public String type(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();String type = sjedis.type(key);sjedis.close();return type;}/*** 查找所有匹配給定的模式的鍵* * @param String* key的表達式,*表示多個,?表示一個* */public Set<String> keys(String pattern) {Jedis jedis = getJedis();Set<String> set = jedis.keys(pattern);jedis.close();return set;}}// *******************************************Sets*******************************************//public class Sets {/*** 向Set添加一條記錄,如果member已存在返回0,否則返回1* * @param String* key* @param String* member* @return 操作碼,0或1* */public long sadd(String key, String member) {Jedis jedis = getJedis();long s = jedis.sadd(key, member);jedis.close();return s;}public long sadd(byte[] key, byte[] member) {Jedis jedis = getJedis();long s = jedis.sadd(key, member);jedis.close();return s;}/*** 獲取給定key中元素個數* * @param String* key* @return 元素個數* */public long scard(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();long len = sjedis.scard(key);sjedis.close();return len;}/*** 返回從第一組和所有的給定集合之間的差異的成員* * @param String* ... keys* @return 差異的成員集合* */public Set<String> sdiff(String... keys) {Jedis jedis = getJedis();Set<String> set = jedis.sdiff(keys);jedis.close();return set;}/*** 這個命令等于sdiff,但返回的不是結果集,而是將結果集存儲在新的集合中,如果目標已存在,則覆蓋。* * @param String* newkey 新結果集的key* @param String* ... keys 比較的集合* @return 新集合中的記錄數* **/public long sdiffstore(String newkey, String... keys) {Jedis jedis = getJedis();long s = jedis.sdiffstore(newkey, keys);jedis.close();return s;}/*** 返回給定集合交集的成員,如果其中一個集合為不存在或為空,則返回空Set* * @param String* ... keys* @return 交集成員的集合* **/public Set<String> sinter(String... keys) {Jedis jedis = getJedis();Set<String> set = jedis.sinter(keys);jedis.close();return set;}/*** 這個命令等于sinter,但返回的不是結果集,而是將結果集存儲在新的集合中,如果目標已存在,則覆蓋。* * @param String* newkey 新結果集的key* @param String* ... keys 比較的集合* @return 新集合中的記錄數* **/public long sinterstore(String newkey, String... keys) {Jedis jedis = getJedis();long s = jedis.sinterstore(newkey, keys);jedis.close();return s;}/*** 確定一個給定的值是否存在* * @param String* key* @param String* member 要判斷的值* @return 存在返回1,不存在返回0* **/public boolean sismember(String key, String member) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();boolean s = sjedis.sismember(key, member);sjedis.close();return s;}/*** 返回集合中的所有成員* * @param String* key* @return 成員集合* */public Set<String> smembers(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();Set<String> set = sjedis.smembers(key);sjedis.close();return set;}public Set<byte[]> smembers(byte[] key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();Set<byte[]> set = sjedis.smembers(key);sjedis.close();return set;}/*** 將成員從源集合移出放入目標集合 <br/>* 如果源集合不存在或不包哈指定成員,不進行任何操作,返回0<br/>* 否則該成員從源集合上刪除,并添加到目標集合,如果目標集合中成員已存在,則只在源集合進行刪除* * @param String* srckey 源集合* @param String* dstkey 目標集合* @param String* member 源集合中的成員* @return 狀態碼,1成功,0失敗* */public long smove(String srckey, String dstkey, String member) {Jedis jedis = getJedis();long s = jedis.smove(srckey, dstkey, member);jedis.close();return s;}/*** 從集合中刪除成員* * @param String* key* @return 被刪除的成員* */public String spop(String key) {Jedis jedis = getJedis();String s = jedis.spop(key);jedis.close();return s;}/*** 從集合中刪除指定成員* * @param String* key* @param String* member 要刪除的成員* @return 狀態碼,成功返回1,成員不存在返回0* */public long srem(String key, String member) {Jedis jedis = getJedis();long s = jedis.srem(key, member);jedis.close();return s;}/*** 合并多個集合并返回合并后的結果,合并后的結果集合并不保存<br/>* * @param String* ... keys* @return 合并后的結果集合* @see sunionstore* */public Set<String> sunion(String... keys) {Jedis jedis = getJedis();Set<String> set = jedis.sunion(keys);jedis.close();return set;}/*** 合并多個集合并將合并后的結果集保存在指定的新集合中,如果新集合已經存在則覆蓋* * @param String* newkey 新集合的key* @param String* ... keys 要合并的集合* **/public long sunionstore(String newkey, String... keys) {Jedis jedis = getJedis();long s = jedis.sunionstore(newkey, keys);jedis.close();return s;}}// *******************************************Hash*******************************************//public class Hash {/*** 從hash中刪除指定的存儲* * @param String* key* @param String* fieid 存儲的名字* @return 狀態碼,1成功,0失敗* */public long hdel(String key, String fieid) {Jedis jedis = getJedis();long s = jedis.hdel(key, fieid);jedis.close();return s;}public long hdel(String key) {Jedis jedis = getJedis();long s = jedis.del(key);jedis.close();return s;}/*** 測試hash中指定的存儲是否存在* * @param String* key* @param String* fieid 存儲的名字* @return 1存在,0不存在* */public boolean hexists(String key, String fieid) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();boolean s = sjedis.hexists(key, fieid);sjedis.close();return s;}/*** 返回hash中指定存儲位置的值* * @param String* key* @param String* fieid 存儲的名字* @return 存儲對應的值* */public String hget(String key, String fieid) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();String s = sjedis.hget(key, fieid);sjedis.close();return s;}public byte[] hget(byte[] key, byte[] fieid) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();byte[] s = sjedis.hget(key, fieid);sjedis.close();return s;}/*** 以Map的形式返回hash中的存儲和值* * @param String* key* @return Map<Strinig,String>* */public Map<String, String> hgetAll(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();Map<String, String> map = sjedis.hgetAll(key);sjedis.close();return map;}/*** 添加一個對應關系* * @param String* key* @param String* fieid* @param String* value* @return 狀態碼 1成功,0失敗,fieid已存在將更新,也返回0* **/public long hset(String key, String fieid, String value) {Jedis jedis = getJedis();long s = jedis.hset(key, fieid, value);jedis.close();return s;}public long hset(String key, String fieid, byte[] value) {Jedis jedis = getJedis();long s = jedis.hset(key.getBytes(), fieid.getBytes(), value);jedis.close();return s;}/*** 添加對應關系,只有在fieid不存在時才執行* * @param String* key* @param String* fieid* @param String* value* @return 狀態碼 1成功,0失敗fieid已存* **/public long hsetnx(String key, String fieid, String value) {Jedis jedis = getJedis();long s = jedis.hsetnx(key, fieid, value);jedis.close();return s;}/*** 獲取hash中value的集合* * @param String* key* @return List<String>* */public List<String> hvals(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<String> list = sjedis.hvals(key);sjedis.close();return list;}/*** 在指定的存儲位置加上指定的數字,存儲位置的值必須可轉為數字類型* * @param String* key* @param String* fieid 存儲位置* @param String* long value 要增加的值,可以是負數* @return 增加指定數字后,存儲位置的值* */public long hincrby(String key, String fieid, long value) {Jedis jedis = getJedis();long s = jedis.hincrBy(key, fieid, value);jedis.close();return s;}/*** 返回指定hash中的所有存儲名字,類似Map中的keySet方法* * @param String* key* @return Set<String> 存儲名稱的集合* */public Set<String> hkeys(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();Set<String> set = sjedis.hkeys(key);sjedis.close();return set;}/*** 獲取hash中存儲的個數,類似Map中size方法* * @param String* key* @return long 存儲的個數* */public long hlen(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();long len = sjedis.hlen(key);sjedis.close();return len;}/*** 根據多個key,獲取對應的value,返回List,如果指定的key不存在,List對應位置為null* * @param String* key* @param String* ... fieids 存儲位置* @return List<String>* */public List<String> hmget(String key, String... fieids) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<String> list = sjedis.hmget(key, fieids);sjedis.close();return list;}public List<byte[]> hmget(byte[] key, byte[]... fieids) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<byte[]> list = sjedis.hmget(key, fieids);sjedis.close();return list;}/*** 添加對應關系,如果對應關系已存在,則覆蓋* * @param Strin* key* @param Map* <String,String> 對應關系* @return 狀態,成功返回OK* */public String hmset(String key, Map<String, String> map) {Jedis jedis = getJedis();String s = jedis.hmset(key, map);jedis.close();return s;}/*** 添加對應關系,如果對應關系已存在,則覆蓋* * @param Strin* key* @param Map* <String,String> 對應關系* @return 狀態,成功返回OK* */public String hmset(byte[] key, Map<byte[], byte[]> map) {Jedis jedis = getJedis();String s = jedis.hmset(key, map);jedis.close();return s;}}// *******************************************Strings*******************************************//public class Strings {/*** 根據key獲取記錄* * @param String* key* @return 值* */public String get(String key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();String value = sjedis.get(key);sjedis.close();return value;}/*** 根據key獲取記錄* * @param byte[] key* @return 值* */public byte[] get(byte[] key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();byte[] value = sjedis.get(key);sjedis.close();return value;}/*** 添加有過期時間的記錄* * @param String* key* @param int seconds 過期時間,以秒為單位* @param String* value* @return String 操作狀態* */public String setEx(String key, int seconds, String value) {Jedis jedis = getJedis();String str = jedis.setex(key, seconds, value);jedis.close();return str;}/*** 添加有過期時間的記錄* * @param String* key* @param int seconds 過期時間,以秒為單位* @param String* value* @return String 操作狀態* */public String setEx(byte[] key, int seconds, byte[] value) {Jedis jedis = getJedis();String str = jedis.setex(key, seconds, value);jedis.close();return str;}/*** 添加一條記錄,僅當給定的key不存在時才插入* * @param String* key* @param String* value* @return long 狀態碼,1插入成功且key不存在,0未插入,key存在* */public long setnx(String key, String value) {Jedis jedis = getJedis();long str = jedis.setnx(key, value);jedis.close();return str;}/*** 添加記錄,如果記錄已存在將覆蓋原有的value* * @param String* key* @param String* value* @return 狀態碼* */public String set(String key, String value) {return set(SafeEncoder.encode(key), SafeEncoder.encode(value));}/*** 添加記錄,如果記錄已存在將覆蓋原有的value* * @param String* key* @param String* value* @return 狀態碼* */public String set(String key, byte[] value) {return set(SafeEncoder.encode(key), value);}/*** 添加記錄,如果記錄已存在將覆蓋原有的value* * @param byte[] key* @param byte[] value* @return 狀態碼* */public String set(byte[] key, byte[] value) {Jedis jedis = getJedis();String status = jedis.set(key, value);jedis.close();return status;}/*** 從指定位置開始插入數據,插入的數據會覆蓋指定位置以后的數據<br/>* 例:String str1="123456789";<br/>* 對str1操作后setRange(key,4,0000),str1="123400009";* * @param String* key* @param long offset* @param String* value* @return long value的長度* */public long setRange(String key, long offset, String value) {Jedis jedis = getJedis();long len = jedis.setrange(key, offset, value);jedis.close();return len;}/*** 在指定的key中追加value* * @param String* key* @param String* value* @return long 追加后value的長度* **/public long append(String key, String value) {Jedis jedis = getJedis();long len = jedis.append(key, value);jedis.close();return len;}/*** 將key對應的value減去指定的值,只有value可以轉為數字時該方法才可用* * @param String* key* @param long number 要減去的值* @return long 減指定值后的值* */public long decrBy(String key, long number) {Jedis jedis = getJedis();long len = jedis.decrBy(key, number);jedis.close();return len;}/*** <b>可以作為獲取唯一id的方法</b><br/>* 將key對應的value加上指定的值,只有value可以轉為數字時該方法才可用* * @param String* key* @param long number 要減去的值* @return long 相加后的值* */public long incrBy(String key, long number) {Jedis jedis = getJedis();long len = jedis.incrBy(key, number);jedis.close();return len;}/*** 對指定key對應的value進行截取* * @param String* key* @param long startOffset 開始位置(包含)* @param long endOffset 結束位置(包含)* @return String 截取的值* */public String getrange(String key, long startOffset, long endOffset) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();String value = sjedis.getrange(key, startOffset, endOffset);sjedis.close();return value;}/*** 獲取并設置指定key對應的value<br/>* 如果key存在返回之前的value,否則返回null* * @param String* key* @param String* value* @return String 原始value或null* */public String getSet(String key, String value) {Jedis jedis = getJedis();String str = jedis.getSet(key, value);jedis.close();return str;}/*** 批量獲取記錄,如果指定的key不存在返回List的對應位置將是null* * @param String* keys* @return List<String> 值得集合* */public List<String> mget(String... keys) {Jedis jedis = getJedis();List<String> str = jedis.mget(keys);jedis.close();return str;}/*** 批量存儲記錄* * @param String* keysvalues 例:keysvalues="key1","value1","key2","value2";* @return String 狀態碼* */public String mset(String... keysvalues) {Jedis jedis = getJedis();String str = jedis.mset(keysvalues);jedis.close();return str;}/*** 獲取key對應的值的長度* * @param String* key* @return value值得長度* */public long strlen(String key) {Jedis jedis = getJedis();long len = jedis.strlen(key);jedis.close();return len;}}// *******************************************Lists*******************************************//public class Lists {/*** List長度* * @param String* key* @return 長度* */public long llen(String key) {return llen(SafeEncoder.encode(key));}/*** List長度* * @param byte[] key* @return 長度* */public long llen(byte[] key) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();long count = sjedis.llen(key);sjedis.close();return count;}/*** 覆蓋操作,將覆蓋List中指定位置的值* * @param byte[] key* @param int index 位置* @param byte[] value 值* @return 狀態碼* */public String lset(byte[] key, int index, byte[] value) {Jedis jedis = getJedis();String status = jedis.lset(key, index, value);jedis.close();return status;}/*** 覆蓋操作,將覆蓋List中指定位置的值* * @param key* @param int index 位置* @param String* value 值* @return 狀態碼* */public String lset(String key, int index, String value) {return lset(SafeEncoder.encode(key), index,SafeEncoder.encode(value));}/*** 在value的相對位置插入記錄* * @param key* @param LIST_POSITION* 前面插入或后面插入* @param String* pivot 相對位置的內容* @param String* value 插入的內容* @return 記錄總數* */public long linsert(String key, LIST_POSITION where, String pivot,String value) {return linsert(SafeEncoder.encode(key), where,SafeEncoder.encode(pivot), SafeEncoder.encode(value));}/*** 在指定位置插入記錄* * @param String* key* @param LIST_POSITION* 前面插入或后面插入* @param byte[] pivot 相對位置的內容* @param byte[] value 插入的內容* @return 記錄總數* */public long linsert(byte[] key, LIST_POSITION where, byte[] pivot,byte[] value) {Jedis jedis = getJedis();long count = jedis.linsert(key, where, pivot, value);jedis.close();return count;}/*** 獲取List中指定位置的值* * @param String* key* @param int index 位置* @return 值* **/public String lindex(String key, int index) {return SafeEncoder.encode(lindex(SafeEncoder.encode(key), index));}/*** 獲取List中指定位置的值* * @param byte[] key* @param int index 位置* @return 值* **/public byte[] lindex(byte[] key, int index) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();byte[] value = sjedis.lindex(key, index);sjedis.close();return value;}/*** 將List中的第一條記錄移出List* * @param String* key* @return 移出的記錄* */public String lpop(String key) {return SafeEncoder.encode(lpop(SafeEncoder.encode(key)));}/*** 將List中的第一條記錄移出List* * @param byte[] key* @return 移出的記錄* */public byte[] lpop(byte[] key) {Jedis jedis = getJedis();byte[] value = jedis.lpop(key);jedis.close();return value;}/*** 將List中最后第一條記錄移出List* * @param byte[] key* @return 移出的記錄* */public String rpop(String key) {Jedis jedis = getJedis();String value = jedis.rpop(key);jedis.close();return value;}/*** 向List尾部追加記錄* * @param String* key* @param String* value* @return 記錄總數* */public long lpush(String key, String value) {return lpush(SafeEncoder.encode(key), SafeEncoder.encode(value));}/*** 向List頭部追加記錄* * @param String* key* @param String* value* @return 記錄總數* */public long rpush(String key, String value) {Jedis jedis = getJedis();long count = jedis.rpush(key, value);jedis.close();return count;}/*** 向List頭部追加記錄* * @param String* key* @param String* value* @return 記錄總數* */public long rpush(byte[] key, byte[] value) {Jedis jedis = getJedis();long count = jedis.rpush(key, value);jedis.close();return count;}/*** 向List中追加記錄* * @param byte[] key* @param byte[] value* @return 記錄總數* */public long lpush(byte[] key, byte[] value) {Jedis jedis = getJedis();long count = jedis.lpush(key, value);jedis.close();return count;}/*** 獲取指定范圍的記錄,可以做為分頁使用* * @param String* key* @param long start* @param long end* @return List* */public List<String> lrange(String key, long start, long end) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<String> list = sjedis.lrange(key, start, end);sjedis.close();return list;}/*** 獲取指定范圍的記錄,可以做為分頁使用* * @param byte[] key* @param int start* @param int end 如果為負數,則尾部開始計算* @return List* */public List<byte[]> lrange(byte[] key, int start, int end) {// ShardedJedis sjedis = getShardedJedis();Jedis sjedis = getJedis();List<byte[]> list = sjedis.lrange(key, start, end);sjedis.close();return list;}/*** 刪除List中c條記錄,被刪除的記錄值為value* * @param byte[] key* @param int c 要刪除的數量,如果為負數則從List的尾部檢查并刪除符合的記錄* @param byte[] value 要匹配的值* @return 刪除后的List中的記錄數* */public long lrem(byte[] key, int c, byte[] value) {Jedis jedis = getJedis();long count = jedis.lrem(key, c, value);jedis.close();return count;}/*** 刪除List中c條記錄,被刪除的記錄值為value* * @param String* key* @param int c 要刪除的數量,如果為負數則從List的尾部檢查并刪除符合的記錄* @param String* value 要匹配的值* @return 刪除后的List中的記錄數* */public long lrem(String key, int c, String value) {return lrem(SafeEncoder.encode(key), c, SafeEncoder.encode(value));}/*** 算是刪除吧,只保留start與end之間的記錄* * @param byte[] key* @param int start 記錄的開始位置(0表示第一條記錄)* @param int end 記錄的結束位置(如果為-1則表示最后一個,-2,-3以此類推)* @return 執行狀態碼* */public String ltrim(byte[] key, int start, int end) {Jedis jedis = getJedis();String str = jedis.ltrim(key, start, end);jedis.close();return str;}/*** 算是刪除吧,只保留start與end之間的記錄* * @param String* key* @param int start 記錄的開始位置(0表示第一條記錄)* @param int end 記錄的結束位置(如果為-1則表示最后一個,-2,-3以此類推)* @return 執行狀態碼* */public String ltrim(String key, int start, int end) {return ltrim(SafeEncoder.encode(key), start, end);}}}6.新建spring-redis.xml 配置redis連接池和bean
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- redis連接池設置 --><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"><!-- 控制一個pool 可以分配多少個jedis實例 --><property name="maxTotal" value="${redis.pool.maxActive}" /><!-- 連接池中最多可空閑 maxIdle個連接,假設設置為20,表示即使沒有數據庫連接依然保持20個空閑連接,隨時處于待命狀態--><property name="maxIdle" value="${redis.pool.maxIdle}" /><!-- 最大等待時間,當沒有可用連接時,連接池等待連接被歸還的最大時間(單位為毫秒),超時則拋出異常 --><property name="maxWaitMillis" value="${redis.pool.maxWait}" /><!-- 在獲取連接時,檢查連接有效性 --><property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /></bean><!-- 創建redis連接池,并做相關配置 --><bean id="jedisWritePool" class="com.artisan.o2o.cache.JedisPoolWriper"depends-on="jedisPoolConfig"><constructor-arg index="0" ref="jedisPoolConfig" /><constructor-arg index="1" value="${redis.hostname}" /><constructor-arg index="2" value="${redis.port}" type="int" /></bean><!-- 創建redis的工具類,封裝好Redis的連接以進行相關的操作 --><bean id="jedisUtil" class="com.artisan.o2o.cache.JedisUtil"scope="singleton"><property name="jedisPool"><ref bean="jedisWritePool" /></property></bean><bean id="jedisKeys" class="com.artisan.o2o.cache.JedisUtil$Keys"scope="singleton"><constructor-arg ref="jedisUtil"></constructor-arg></bean><bean id="jedisStrings" class="com.artisan.o2o.cache.JedisUtil$Strings"scope="singleton"><constructor-arg ref="jedisUtil"></constructor-arg></bean><bean id="jedisLists" class="com.artisan.o2o.cache.JedisUtil$Lists"scope="singleton"><constructor-arg ref="jedisUtil"></constructor-arg></bean><bean id="jedisSets" class="com.artisan.o2o.cache.JedisUtil$Sets"scope="singleton"><constructor-arg ref="jedisUtil"></constructor-arg></bean><bean id="jedisHash" class="com.artisan.o2o.cache.JedisUtil$Hash"scope="singleton"><constructor-arg ref="jedisUtil"></constructor-arg></bean></beans>7. web.xml中加載spring-redis.xml
檢查下即可
8.Service層使用緩存
首先從緩存中取,如果緩存中不存在則去DB中獲取然后更新到緩存中,下次直接從緩存中獲取。
package com.artisan.o2o.service.impl;import java.io.IOException; import java.util.ArrayList; import java.util.List;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import com.artisan.o2o.cache.JedisUtil; import com.artisan.o2o.dao.AreaDao; import com.artisan.o2o.entity.Area; import com.artisan.o2o.service.AreaService; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;/*** * * @ClassName: AreaServiceImpl* * @Description: @Service標注的服務層* * @author: Mr.Yang* * @date: 2018年5月14日 下午9:06:45*/ @Service public class AreaServiceImpl implements AreaService {@AutowiredAreaDao areaDao;@Autowiredprivate JedisUtil.Strings jedisStrings;@Autowiredprivate JedisUtil.Keys jedisKeys;private static String AREALISTKEY = "arealist";@Overridepublic List<Area> getAreaList() throws JsonParseException, JsonMappingException, IOException {// 定義redis中的keyString key = AREALISTKEY;// 定義接收對象List<Area> areaList = null;// 定義jackson數據轉換操作類ObjectMapper mapper = new ObjectMapper();// 判斷key是否存在if (!jedisKeys.exists(key)) {areaList = areaDao.queryArea();String jsonString = mapper.writeValueAsString(areaList);jedisStrings.set(key, jsonString);} else {String jsonString = jedisStrings.get(key);JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Area.class);areaList = mapper.readValue(jsonString, javaType);}return areaList;}}9.單元測試
9.1 BaseTest基類中加載 classpath:spring-redis.xml
package com.artisan.o2o;import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** * * @ClassName: BaseTest* * @Description: 測試類的基類,配置Spring和junit整合,junit啟動時加載springIOC容器* * @author: Mr.Yang* * @date: 2018年5月14日 下午12:58:21*/@RunWith(SpringJUnit4ClassRunner.class) // 告訴junit spring配置文件 @ContextConfiguration({ "classpath:spring/spring-dao.xml", "classpath:spring-service.xml", "classpath:spring-redis.xml" }) public class BaseTest {}9.2 debug調測
package com.artisan.o2o.service;import java.io.IOException; import java.util.List;import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired;import com.artisan.o2o.BaseTest; import com.artisan.o2o.entity.Area; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException;public class AreaServiceTest extends BaseTest {@AutowiredAreaService areaService;@Testpublic void testGetAreaList() throws JsonParseException, JsonMappingException, IOException {List<Area> areaList = areaService.getAreaList();Assert.assertEquals("北京", areaList.get(0).getAreaName());} }getAreaList方法中加入斷點,逐步調測。 測試兩次,第一次從db中獲取,第二次從redis中讀取. 單元測試通過
10 Redis中驗證數據
自帶客戶端 get arealist
第三方客戶端
Github地址
代碼地址: https://github.com/yangshangwei/o2o
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的实战SSM_O2O商铺_45【Redis缓存】配置Redis在Service层加入缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实战SSM_O2O商铺_44【DES加密
- 下一篇: 实战SSM_O2O商铺_46【Redis