簡單示例:Spring4 整合 單個Redis服務


1. 引入spring-data-redis.jar

  API:https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/package-summary.html#package.description

2. spring配置文件添加如下配置

<!-- redis配置 -->
    <context:property-placeholder location="classpath:redis.properties" />
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxTotal" value="${redis.maxTotal}" />
        <!--<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        <!--<property name="testOnReturn" value="${redis.testOnReturn}" />-->
        <!--<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" />-->
    </bean>

    <!--<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"-->
        <!--p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:poolConfig-ref="poolConfig"/>-->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}" p:port="${redis.port}" p:poolConfig-ref="poolConfig"/>

<!-- SDR默認采用的序列化策略有兩種,一種是String的序列化策略,一種是JDK的序列化策略。 StringRedisTemplate默認采用的是String的序列化策略,保存的key和value都是采
用此策略序列化保存的。 RedisTemplate默認采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。 就是因為序列化策略的不同,即使是同一個key用不同的
Template去序列化,結果是不同的。所以根據key去刪除數據的時候就出現了刪除失敗的問題。 --> <!-- redis 序列化策略 ,通常情況下key值采用String序列化策略, -->

<!-- 如果不指定序列化策略,StringRedisTemplate的key和value都將采用String序列化策略; -->
<!-- 但是RedisTemplate的key和value都將采用JDK序列化 這樣就會出現采用不同template保存的數據不能用同一個template刪除的問題 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> <property name="enableTransactionSupport" value="true" /> </bean>
# Redis settings

#redis的服務器地址
redis.host=localhost
#redis的服務端口
redis.port=6379
#密碼
redis.pass=123

#最大空閑數
redis.maxIdle=300
#最大總數
redis.maxTotal=1000
#指明是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接並嘗試取出另一個
redis.testOnBorrow=true

 

 

3. Redis工具類

package com.*;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

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

/**
 * Created by Administrator on 2017/3/8.
 */
@Component
public class RedisManager<T> {
    private Logger log = Logger.getLogger(RedisManager.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /** =================================== Hash ====================================================**/

    /**
     * 緩存Map
     *
     * @param key
     * @param hashKey
     * @param t
     * @return
     */
    public void setCacheMap(String key, String hashKey, T t) {
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(key);
        boundHashOperations.put(hashKey, t);
//        boundHashOperations.expire(BasConstant.MEMORY_TOKEN_EXPIRES, TimeUnit.DAYS);
//        redisTemplate.opsForValue().set(realToken, studentVo, BasConstant.TOKEN_EXPIRES_HOUR, TimeUnit.DAYS);
        //存儲到redis並設置過期時間
//        redisTemplate.boundValueOps(realToken).set(studentVo, BasConstant.TOKEN_EXPIRES_HOUR, TimeUnit.DAYS);
    }

    /**
     * 獲得緩存的Map
     *
     * @param key //* @param hashOperation
     * @return
     */
    public <T> Map<String, T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/) {
        Map<String, T> map = redisTemplate.opsForHash().entries(key);
        /*Map<String, T> map = hashOperation.entries(key);*/
        return map;
    }

    /**
     * 獲取緩存的map大小
     *
     * @param key
     * @return
     */
    public long getCacheMapSize(String key) {
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 獲取map的value值
     *
     * @param key     key
     * @param hashKey field
     * @return
     */
    public Object getMapValue(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    /**
     * 是否存在 key 及 field
     *
     * @param key     key
     * @param hashKey field
     * @return
     */
    public boolean hasHashKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    /**
     * 延期
     *
     * @param key
     * @return
     */
    public boolean expireHash(String key, long time) {
        return redisTemplate.boundHashOps(key).expire(time, TimeUnit.DAYS);
    }

    /**
     * 從redis中刪除key緩存
     *
     * @param key
     */
    public void deleteHashKey(String key, Object... hashKeys) {
        redisTemplate.opsForHash().delete(key, hashKeys);
    }

    /** =================================== 通用 ====================================================**/

    /**
     * 從redis中刪除key緩存
     *
     * @param key
     */
    public void deleteKey(String key, Object... hashKeys) {
        redisTemplate.delete(key);
    }

    /**
     * 是否存在key
     *
     * @param key
     * @return 是否存在key
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 延期
     *
     * @param key 鍵值
     * @return
     */
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        return redisTemplate.expire(key, time, timeUnit);
    }

    /** =================================== List ====================================================**/

    /**
     * list緩存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setCacheList(String key, String value) {
        try {
            ListOperations<String, String> listOps = redisTemplate.opsForList();
            listOps.rightPush(key, value);
            return true;
        } catch (Throwable t) {
            log.error("緩存[" + key + "]失敗, value[" + value + "]", t);
        }
        return false;
    }

    public void setValueForList(String key, long index, Object value){
        BoundListOperations listOps = redisTemplate.boundListOps(key);
        listOps.set(index, value);
    }

    /**
     * 緩存list
     *
     * @param key  鍵值
     * @param list value
     * @return
     */
    public void setCacheList(String key, List list) {
        BoundListOperations listOps = redisTemplate.boundListOps(key);
        //只能以數組形式存放
        listOps.rightPushAll(list.toArray());
    }

    /**
     * 獲取list緩存 - 根據起始~終止位置
     *
     * @param key   鍵值
     * @param start 起始位置
     * @param end   截止位置
     * @return
     */
    public List getList(String key, long start, long end) {
        List list = null;
        try {
            BoundListOperations listOperations = redisTemplate.boundListOps(key);
            list = listOperations.range(start, end);
        } catch (Throwable t) {
            log.error("獲取list緩存失敗key[" + key + ", error[" + t + "]");
        }
        return list;
    }

    /**
     * 獲取list緩存 - 根據索引位置
     *
     * @param key 鍵值
     * @param i   索引位置
     * @return
     */
    public Object getCacheList(String key, int i) {
        BoundListOperations listOps = redisTemplate.boundListOps(key);
        return listOps.index(i);
    }

    /**
     * 獲取總條數, 可用於分頁
     *
     * @param key
     * @return
     */
    public long getCacheListSize(String key) {
        BoundListOperations listOps = redisTemplate.boundListOps(key);
        return listOps.size();
    }
}

4. 在service中引入使用工具類操作redis

 


免責聲明!

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



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