SpringBoot整合Redis


======================手動整合=====================

1.手動整合,也就是工具類自己添加緩存

  手動整合只需要三步驟:pom.xml引入依賴、配置redis相關設置、 引入redis工具類:

(1)只需要引入下面這個工具類,會自動引入相關依賴的jar包:

        <!-- 引入 redis 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

 

(2)applications.properties添加如下配置

  如果查看默認值我們可以去查看自動配置的類:RedisAutoConfiguration.class。里面的RedisProperties是相關的默認配置以及生效的配置。

############################################################
#
# REDIS 配置
#
############################################################
# Redis數據庫索引(默認為0)
spring.redis.database=1
# Redis服務器地址
spring.redis.host=localhost
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=1000
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=10
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=2
# 連接超時時間(毫秒)
spring.redis.timeout=0

 

(3)引入redis工具類==這里使用spring-redis-data自帶的StringRedisTemplate

package cn.qlq.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.qlq.bean.user.User;
import cn.qlq.utils.JSONResultUtil;

@RestController
@RequestMapping("redis")
public class RedisController {
    @Autowired
    private StringRedisTemplate strRedis;

    @RequestMapping("/set")
    public JSONResultUtil test() {
        strRedis.opsForValue().set("mycache", "我存入的第一個cache");
        return JSONResultUtil.ok();
    }

    @RequestMapping("/setUser")
    public JSONResultUtil setUser() {
        User user = new User();
        user.setAddress("地址");
        user.setCreatetime(new Date());
        strRedis.opsForValue().set("user", JSONObject.toJSONString(user));
        return JSONResultUtil.ok();
    }

    @RequestMapping("/getUser")
    public JSONResultUtil getUser() {
        String string = strRedis.opsForValue().get("user");
        User user = JSONObject.parseObject(string, User.class);
        System.out.println(user);
        return JSONResultUtil.ok();
    }
}

 

  這里使用StringRedisTemplate類,該類位於spring-data-redis-xxx.jar中,其有五種操作方式:

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

  該類在操作的時候也可以指定key的失效時間,如下:

strRedis.opsForValue().set("mycache", "我存入的第一個cache", 660,TimeUnit.SECONDS);

  關於該類的詳細使用參考:https://www.jianshu.com/p/7bf5dc61ca06

(4)訪問后通過redis客戶端查看內容

 

 補充:編寫一個簡單的工具類對上面的操作進行封裝:

package cn.qlq.utils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // Key(鍵),簡單的key-value操作

    /**
     * 實現命令:TTL key,以秒為單位,返回給定 key的剩余生存時間(TTL, time to live)。
     * 
     * @param key
     * @return
     */
    public long ttl(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 實現命令:expire 設置過期時間,單位秒
     * 
     * @param key
     * @return
     */
    public void expire(String key, long timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 實現命令:INCR key,增加key一次
     * 
     * @param key
     * @return
     */
    public long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 實現命令:KEYS pattern,查找所有符合給定模式 pattern的 key
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 實現命令:DEL key,刪除一個key
     * 
     * @param key
     */
    public void del(String key) {
        redisTemplate.delete(key);
    }

    // String(字符串)

    /**
     * 實現命令:SET key value,設置一個key-value(將字符串值 value關聯到 key)
     * 
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 實現命令:SET key value EX seconds,設置key-value和超時時間(秒)
     * 
     * @param key
     * @param value
     * @param timeout
     *            (以秒為單位)
     */
    public void set(String key, String value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 實現命令:GET key,返回 key所關聯的字符串值。
     * 
     * @param key
     * @return value
     */
    public String get(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    // Hash(哈希表)

    /**
     * 實現命令:HSET key field value,將哈希表 key中的域 field的值設為 value
     * 
     * @param key
     * @param field
     * @param value
     */
    public void hset(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 實現命令:HGET key field,返回哈希表 key中給定域 field的值
     * 
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        return (String) redisTemplate.opsForHash().get(key, field);
    }

    /**
     * 實現命令:HDEL key field [field ...],刪除哈希表 key 中的一個或多個指定域,不存在的域將被忽略。
     * 
     * @param key
     * @param fields
     */
    public void hdel(String key, Object... fields) {
        redisTemplate.opsForHash().delete(key, fields);
    }

    /**
     * 實現命令:HGETALL key,返回哈希表 key中,所有的域和值。
     * 
     * @param key
     * @return
     */
    public Map<Object, Object> hgetall(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    // List(列表)

    /**
     * 實現命令:LPUSH key value,將一個值 value插入到列表 key的表頭
     * 
     * @param key
     * @param value
     * @return 執行 LPUSH命令后,列表的長度。
     */
    public long lpush(String key, String value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 實現命令:LPOP key,移除並返回列表 key的頭元素。
     * 
     * @param key
     * @return 列表key的頭元素。
     */
    public String lpop(String key) {
        return (String) redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 實現命令:RPUSH key value,將一個值 value插入到列表 key的表尾(最右邊)。
     * 
     * @param key
     * @param value
     * @return 執行 LPUSH命令后,列表的長度。
     */
    public long rpush(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

}

 

使用方法如下: 注入到需要的緩存對象中

package cn.qlq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.qlq.bean.user.User;
import cn.qlq.utils.JSONResultUtil;
import cn.qlq.utils.RedisUtils;

@RestController
@RequestMapping("redis")
public class RedisController {

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/getUserByUtils")
    public JSONResultUtil getUserByUtils() {
        String string = (String) redisUtils.get("user");
        User user = JSONObject.parseObject(string, User.class);
        System.out.println(user);
        return JSONResultUtil.ok();
    }
}

 

2.整合注解redis緩存

  這個整合只不過是將xml配置的方式改為基於java配置的方式進行,之前的xml整合過程已經寫的非常詳細,參考:https://www.cnblogs.com/qlqwjy/p/8574121.html

定義cacheManager、redisTemplate、keyGenerator,並用注解聲明開啟緩存。

package cn.qlq.config;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
// 聲明開啟緩存
@EnableCaching
public class RedisCacheConfig {
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        // 多個緩存的名稱,目前只定義了一個(如果這里指定了緩存,后面的@Cacheable的value必須是這里的值)
        rcm.setCacheNames(Arrays.asList("usersCache", "logsCache"));
        // 設置緩存過期時間(秒)
        rcm.setDefaultExpiration(600);
        return rcm;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(factory);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(genericJackson2JsonRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        template.setEnableTransactionSupport(true);

        return template;
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... params) {
                // 規定 本類名+方法名+參數名 為key
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append("-");
                sb.append(method.getName());
                sb.append("-");
                for (Object param : params) {
                    sb.append(param.toString());
                }
                return sb.toString();
            }
        };
    }
}

 

使用方法如下:在使用的地方注解加緩存即可,注意使用更換后的keyGenerator

    /**
     * 分頁查詢user
     * 
     * @param condition
     * @return
     */
    @RequestMapping("getUsers")
    @Cacheable(value = "usersCache", keyGenerator = "keyGenerator") // 在redis中開啟key為findAllUser開頭的存儲空間
    @MyLogAnnotation(operateDescription = "分頁查詢用戶")
    @ResponseBody
    public PageInfo<User> getUsers(@RequestParam Map condition) {
        int pageNum = 1;
        if (ValidateCheck.isNotNull(MapUtils.getString(condition, "pageNum"))) { // 如果不為空的話改變當前頁號
            pageNum = Integer.parseInt(MapUtils.getString(condition, "pageNum"));
        }
        int pageSize = DefaultValue.PAGE_SIZE;
        if (ValidateCheck.isNotNull(MapUtils.getString(condition, "pageSize"))) { // 如果不為空的話改變當前頁大小
            pageSize = Integer.parseInt(MapUtils.getString(condition, "pageSize"));
        }
        // 開始分頁
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = new ArrayList<User>();
        try {
            users = userService.getUsers(condition);
        } catch (Exception e) {
            logger.error("getUsers error!", e);
        }
        PageInfo<User> pageInfo = new PageInfo<User>(users);
        return pageInfo;
    }

 

  注意@Cacheable的key和keyGenerator是互斥的,兩個只能使用一個,查看@Cacheable的源碼也可以知道

結果:

補充:在定義了template之后整合了一個更強大的redis工具類

 在RedisCacheConfig中聲明bean:

    @Bean
    public RedisTemplateUtils redisTemplateUtils(RedisTemplate redisTemplate) {
        RedisTemplateUtils redisTemplateUtils = new RedisTemplateUtils();
        redisTemplateUtils.setRedisTemplate(redisTemplate);
        return redisTemplateUtils;
    }

 

工具類如下:

package cn.qlq.utils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

/**
 * 
 * @author QLQ 基於spring和redis的redisTemplate工具類 針對所有的hash 都是以h開頭的方法 針對所有的Set
 *         都是以s開頭的方法 不含通用方法 針對所有的List 都是以l開頭的方法
 */
public class RedisTemplateUtils {

    private RedisTemplate<String, Object> redisTemplate;

    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // =============================common============================
    /**
     * 指定緩存失效時間
     * 
     * @param key
     *            鍵
     * @param time
     *            時間(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根據key 獲取過期時間
     * 
     * @param key
     *            鍵 不能為null
     * @return 時間(秒) 返回0代表為永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判斷key是否存在
     * 
     * @param key
     *            鍵
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 刪除緩存
     * 
     * @param key
     *            可以傳一個值 或多個
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    // ============================String=============================
    /**
     * 普通緩存獲取
     * 
     * @param key
     *            鍵
     * @return*/
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通緩存放入
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @return true成功 false失敗
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 普通緩存放入並設置時間
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @param time
     *            時間(秒) time要大於0 如果time小於等於0 將設置無限期
     * @return true成功 false 失敗
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 遞增
     * 
     * @param key
     *            鍵
     * @param by
     *            要增加幾(大於0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞增因子必須大於0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 遞減
     * 
     * @param key
     *            鍵
     * @param by
     *            要減少幾(小於0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞減因子必須大於0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================Map=================================
    /**
     * HashGet
     * 
     * @param key
     *            鍵 不能為null
     * @param item
     *            項 不能為null
     * @return*/
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 獲取hashKey對應的所有鍵值
     * 
     * @param key
     *            鍵
     * @return 對應的多個鍵值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * 
     * @param key
     *            鍵
     * @param map
     *            對應多個鍵值
     * @return true 成功 false 失敗
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 並設置時間
     * 
     * @param key
     *            鍵
     * @param map
     *            對應多個鍵值
     * @param time
     *            時間(秒)
     * @return true成功 false失敗
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一張hash表中放入數據,如果不存在將創建
     * 
     * @param key
     *            鍵
     * @param item
     *            項
     * @param value
     *            值
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一張hash表中放入數據,如果不存在將創建
     * 
     * @param key
     *            鍵
     * @param item
     *            項
     * @param value
     *            值
     * @param time
     *            時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 刪除hash表中的值
     * 
     * @param key
     *            鍵 不能為null
     * @param item
     *            項 可以使多個 不能為null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判斷hash表中是否有該項的值
     * 
     * @param key
     *            鍵 不能為null
     * @param item
     *            項 不能為null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash遞增 如果不存在,就會創建一個 並把新增后的值返回
     * 
     * @param key
     *            鍵
     * @param item
     *            項
     * @param by
     *            要增加幾(大於0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash遞減
     * 
     * @param key
     *            鍵
     * @param item
     *            項
     * @param by
     *            要減少記(小於0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================set=============================
    /**
     * 根據key獲取Set中的所有值
     * 
     * @param key
     *            鍵
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根據value從一個set中查詢,是否存在
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將數據放入set緩存
     * 
     * @param key
     *            鍵
     * @param values
     *            值 可以是多個
     * @return 成功個數
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 將set數據放入緩存
     * 
     * @param key
     *            鍵
     * @param time
     *            時間(秒)
     * @param values
     *            值 可以是多個
     * @return 成功個數
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 獲取set緩存的長度
     * 
     * @param key
     *            鍵
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值為value的
     * 
     * @param key
     *            鍵
     * @param values
     *            值 可以是多個
     * @return 移除的個數
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================

    /**
     * 獲取list緩存的內容
     * 
     * @param key
     *            鍵
     * @param start
     *            開始
     * @param end
     *            結束 0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 獲取list緩存的長度
     * 
     * @param key
     *            鍵
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通過索引 獲取list中的值
     * 
     * @param key
     *            鍵
     * @param index
     *            索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 將list放入緩存
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @param time
     *            時間(秒)
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將list放入緩存
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @param time
     *            時間(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將list放入緩存
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @param time
     *            時間(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將list放入緩存
     * 
     * @param key
     *            鍵
     * @param value
     *            值
     * @param time
     *            時間(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根據索引修改list中的某條數據
     * 
     * @param key
     *            鍵
     * @param index
     *            索引
     * @param value
     *            值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N個值為value
     * 
     * @param key
     *            鍵
     * @param count
     *            移除多少個
     * @param value
     *            值
     * @return 移除的個數
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}

 

 

使用方法:

    @Autowired
    private RedisTemplateUtils redisTemplateUtils;

    @RequestMapping("/setUserByUtils2")
    public JSONResultUtil setUserByUtils2() {
        redisTemplateUtils.set("mm", "mm");
        return JSONResultUtil.ok();
    }

    @RequestMapping("/getUserByUtils2")
    public JSONResultUtil getUserByUtils2() {
        String string = (String) redisTemplateUtils.get("mm");
        System.out.println(string);
        return JSONResultUtil.ok();
    }

 

 

===============使用springboot的自動整合(不推薦)===============

 1.Redis單機版:

(1)第一種:springBootStrap自動配置:

  • 目錄結構

 

  • 引入spring-boot-starter-redis.jar
        <!-- 自動配置Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>

 

  • SpringBoot運行類打注解開啟redis緩存
package cn.qlq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching//開啟redis緩存
public class MySpringBootApplication {
    
    public static void main(String[] args) {        
        //入口運行類
        SpringApplication.run(MySpringBootApplication.class, args);
    }

}

 

  • application.properties添加redis配置
server.port=80

logging.level.org.springframework=DEBUG
#springboot   mybatis
#jiazai mybatis peizhiwenjian
#mybatis.mapper-locations = classpath:mapper/*Mapper.xml
#mybatis.config-location = classpath:mapper/config/sqlMapConfig.xml
#mybatis.type-aliases-package = cn.qlq.bean

#shujuyuan
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456


#redis spring.redis.host=localhost spring.redis.port=6379

 

  • Service中打緩存注解:
package cn.qlq.service.impl;


import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import cn.qlq.bean.User;
import cn.qlq.mapper.UserMapper;
import cn.qlq.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
 @Cacheable(value="findAllUser",key="1")//在redis中開啟key為findAllUser開頭的存儲空間
    public List<User> findAllUser(Map condition) {
        System.out.println("打印語句則沒有走緩存");
        List<User> list = userMapper.findAll();
        return list;
    }

    @Override
 @CacheEvict(value="findAllUser",allEntries=true)//執行此方法的時候刪除上面的緩存(以findAllUser為名稱的)
    public int addUser() throws SQLException {
        // TODO Auto-generated method stub
        return userMapper.addUser();
    }

}

 

  •  測試:

(1)訪問:http://localhost/list?name=1(第一次不走緩存)

 

再次訪問:

  沒有打印語句,也就是沒有走方法。

(2)http://localhost/list?name=2(第一次不走緩存)

再次訪問:

  沒有打印語句,也就是沒有走方法。

(3)訪問:http://localhost/list?name=1

  沒有打印語句,也就是沒有走方法。還是走的緩存。

查看Redis緩存的key:

 

RedisDesktopManager查看:

 

  • 測試清除緩存:

查看Redis緩存的key發現為空:

 

  總結:

    注解上的findAllUser是key的前綴,相當於findAllUser:xxxx,后面的是spring自動根據函數的參數生成,如果redis存在則不走方法,直接取出緩存,如果是參數不同,則走方法且加入緩存。

      清除緩存的時候只會清除緩存key前綴是findAllUser開頭的,如果是自己手動添加的以findAllUser:開頭的也會被清除。如下面的在執行add方法的時候也會被清除:

127.0.0.1:6379> set findAllUser:mykey test
OK

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM