springboot 集成 redis

springboot 集成 redis,第1张

springboot 集成 redis

    org.springframework.boot
    spring-boot-starter-data-redis
    2.0.0.RELEASE
    
        
            lettuce-core
            io.lettuce
        
    



    redis.clients
    jedis
    2.10.0

# Redis数据库索引()
spring.redis.database=*
# Redis服务器地址
spring.redis.host=***
# Redis服务器连接密码(默认为空)
spring.redis.password=***
# Redis服务器连接端口
spring.redis.port=***
# 连接超时时间(毫秒)
spring.redis.timeout=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0

package com.util;

import lombok.Getter;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil {

    //region   设置注入的redis对象

    //    public RedisUtil(RedisTemplate template) {
//        stringRedisTemplate=template;
    //    }

    @Getter
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "defaultRedisTemplate")
    private StringRedisTemplate defaultRedisTemplate;

    @Resource(name = "cacheRedisTemplate")
    private StringRedisTemplate cacheRedisTemplate;

    @Resource(name ="defaultRedisFactory" )
    private JedisConnectionFactory jedisConnectionFactory;


    private static RedisUtil redisUtil;

    
    @PostConstruct
    public void init() {
        redisUtil = this;
        redisUtil.defaultRedisTemplate= this.defaultRedisTemplate;
        redisUtil.cacheRedisTemplate= this.cacheRedisTemplate;
        redisUtil.stringRedisTemplate = this.defaultRedisTemplate;

    }

    public void setDefaultRedisTemplate(){
        this.stringRedisTemplate=defaultRedisTemplate;
    }

    public void setCacheRedisTemplate(){
        this.stringRedisTemplate=cacheRedisTemplate;
    }



//endregion

    //region redis实例重启

    public void validateObject(final Object obj) {
        boolean closed = stringRedisTemplate.getConnectionFactory().getConnection().isClosed();
        if (closed) {
//            Jedis jedis = stringRedisTemplate.getConnectionFactory().getConnection().getNativeConnection();
            RedisConnection jedisConnection = jedisConnectionFactory.getConnection();
            Jedis jedis = (Jedis)jedisConnection.getNativeConnection();
        }
    }

    //endregion

    
    //region key相关 *** 作

    
    public Boolean delete(String key) {
        stringRedisTemplate.delete(key);
        return true;
    }

    
    public Boolean delete(Collection keys) {
        stringRedisTemplate.delete(keys);
        return true;
    }

    
    public byte[] dump(String key) {
        return stringRedisTemplate.dump(key);
    }

    
    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        return stringRedisTemplate.expire(key, timeout, unit);
    }

    
    public Boolean expireAt(String key, Date date) {
        return stringRedisTemplate.expireAt(key, date);
    }

    
    public Set keys(String pattern) {
        return stringRedisTemplate.keys(pattern);
    }
    public Set scan(String pattern){
        HashSet set = new HashSet<>();
        RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection();
        Cursor c = connection.scan(new ScanOptions.ScanOptionsBuilder().match(pattern).build());
        while (c.hasNext()) {
            set.add(new String(c.next()));
        }
        return set;
        


    }


    
    public Boolean move(String key, int dbIndex) {
        return stringRedisTemplate.move(key, dbIndex);
    }

    
    public Boolean persist(String key) {
        return stringRedisTemplate.persist(key);
    }

    
    public Long getExpire(String key, TimeUnit unit) {
        return stringRedisTemplate.getExpire(key, unit);
    }

    
    public Long getExpire(String key) {
        return stringRedisTemplate.getExpire(key);
    }

    
    public String randomKey() {
        return stringRedisTemplate.randomKey();
    }

    
    public void rename(String oldKey, String newKey) {
        stringRedisTemplate.rename(oldKey, newKey);
    }

    
    public Boolean renameIfAbsent(String oldKey, String newKey) {
        return stringRedisTemplate.renameIfAbsent(oldKey, newKey);
    }

    
    public DataType type(String key) {
        return stringRedisTemplate.type(key);
    }




    //endregion


    
    //region string相关 *** 作



    
    public void setByDays( String key , String value , long howManyDays  ){
        stringRedisTemplate.opsForValue().set(key, value, howManyDays, TimeUnit.DAYS);
    }

    
    public void setBySeconds( String key , String value , long howManySeconds ){
        stringRedisTemplate.opsForValue().set(key, value, howManySeconds, TimeUnit.SECONDS);
    }


    
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    
    public String get(String key) {
        String val = stringRedisTemplate.opsForValue().get(key);
        if (val == null) {
            return null;
        } else {
            return stringRedisTemplate.opsForValue().get(key).toString();
        }
    }

    
    public String getRange(String key, long start, long end) {
        return stringRedisTemplate.opsForValue().get(key, start, end);
    }

    
    public String getAndSet(String key, String value) {
        return stringRedisTemplate.opsForValue().getAndSet(key, value).toString();
    }

    
    public Boolean getBit(String key, long offset) {
        return stringRedisTemplate.opsForValue().getBit(key, offset);
    }

    
    public List multiGet(Collection keys) {
        return stringRedisTemplate.opsForValue().multiGet(keys);
    }

    
    public boolean setBit(String key, long offset, boolean value) {
        return stringRedisTemplate.opsForValue().setBit(key, offset, value);
    }

    
    public void setEx(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    
    public boolean setIfAbsent(String key, String value) {
        return stringRedisTemplate.opsForValue().setIfAbsent(key, value);
    }

    
    public void setRange(String key, String value, long offset) {
        stringRedisTemplate.opsForValue().set(key, value, offset);
    }

    
    public Long size(String key) {
        return stringRedisTemplate.opsForValue().size(key);
    }

    
    public void multiSet(Map maps) {
        stringRedisTemplate.opsForValue().multiSet(maps);
    }

    
    public boolean multiSetIfAbsent(Map maps) {
        return stringRedisTemplate.opsForValue().multiSetIfAbsent(maps);
    }

    
    public Long incrBy(String key, long increment) {
        return stringRedisTemplate.opsForValue().increment(key, increment);
    }

    
    public Double incrByFloat(String key, double increment) {
        return stringRedisTemplate.opsForValue().increment(key, increment);
    }

    
    public Integer append(String key, String value) {
        return stringRedisTemplate.opsForValue().append(key, value);
    }


    //endregion


    
    //region hash相关 *** 作

    
    public Object hGet(String key, String field) {
        return stringRedisTemplate.opsForHash().get(key, field);
    }

    
    public Map hGetAll(String key) {
        return stringRedisTemplate.opsForHash().entries(key);
    }

    
    public List hMultiGet(String key, Collection fields) {
        return stringRedisTemplate.opsForHash().multiGet(key, fields);
    }

    
    public void hPut(String key, String hashKey, String value) {
        stringRedisTemplate.opsForHash().put(key, hashKey, value);
    }

    
    public void hPutAll(String key, Map maps) {
        stringRedisTemplate.opsForHash().putAll(key, maps);
    }

    
    public Boolean hPutIfAbsent(String key, String hashKey, String value) {
        return stringRedisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
    }

    
    public Long hDelete(String key, Object... fields) {
        return stringRedisTemplate.opsForHash().delete(key, fields);
    }

    
    public boolean hExists(String key, String field) {
        return stringRedisTemplate.opsForHash().hasKey(key, field);
    }

    
    public Long hIncrBy(String key, Object field, long increment) {
        return stringRedisTemplate.opsForHash().increment(key, field, increment);
    }

    
    public Double hIncrByFloat(String key, Object field, double delta) {
        return stringRedisTemplate.opsForHash().increment(key, field, delta);
    }

    
    public Set hKeys(String key) {
        return stringRedisTemplate.opsForHash().keys(key);
    }

    
    public Long hSize(String key) {
        return stringRedisTemplate.opsForHash().size(key);
    }

    
    public List hValues(String key) {
        return stringRedisTemplate.opsForHash().values(key);
    }

    
    public Cursor> hScan(String key, ScanOptions options) {
        return stringRedisTemplate.opsForHash().scan(key, options);
    }
    //endregion

    
    //region list相关 *** 作

    
    public String lIndex(String key, long index) {
        return stringRedisTemplate.opsForList().index(key, index).toString();
    }

    
    public List lRange(String key, long start, long end) {
        return stringRedisTemplate.opsForList().range(key, start, end);
    }

    
    public Long lLeftPush(String key, String value) {
        return stringRedisTemplate.opsForList().leftPush(key, value);
    }

    
    public Long lLeftPushAll(String key, String... value) {
        return stringRedisTemplate.opsForList().leftPushAll(key, value);
    }

    
    public Long lLeftPushAll(String key, Collection value) {
        return stringRedisTemplate.opsForList().leftPushAll(key, value);
    }

    
    public Long lLeftPushIfPresent(String key, String value) {
        return stringRedisTemplate.opsForList().leftPushIfPresent(key, value);
    }

    
    public Long lLeftPush(String key, String pivot, String value) {
        return stringRedisTemplate.opsForList().leftPush(key, pivot, value);
    }

    
    public Long lRightPush(String key, String value) {
        return stringRedisTemplate.opsForList().rightPush(key, value);
    }

    
    public Long lRightPushAll(String key, String... value) {
        return stringRedisTemplate.opsForList().rightPushAll(key, value);
    }

    
    public Long lRightPushAll(String key, Collection value) {
        return stringRedisTemplate.opsForList().rightPushAll(key, value);
    }

    
    public Long lRightPushIfPresent(String key, String value) {
        return stringRedisTemplate.opsForList().rightPushIfPresent(key, value);
    }

    
    public Long lRightPush(String key, String pivot, String value) {
        return stringRedisTemplate.opsForList().rightPush(key, pivot, value);
    }

    
    public void lSet(String key, long index, String value) {
        stringRedisTemplate.opsForList().set(key, index, value);
    }

    
    public String lLeftPop(String key) {
        return stringRedisTemplate.opsForList().leftPop(key).toString();
    }

    
    public String lBLeftPop(String key, long timeout, TimeUnit unit) {
        return stringRedisTemplate.opsForList().leftPop(key, timeout, unit).toString();
    }

    
    public String lRightPop(String key) {
        return stringRedisTemplate.opsForList().rightPop(key).toString();
    }

    
    public String lBRightPop(String key, long timeout, TimeUnit unit) {
        return stringRedisTemplate.opsForList().rightPop(key, timeout, unit).toString();
    }

    
    public String lRightPopAndLeftPush(String sourceKey, String destinationKey) {
        return stringRedisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
                destinationKey).toString();
    }

    
    public String lBRightPopAndLeftPush(String sourceKey, String destinationKey,
                                        long timeout, TimeUnit unit) {
        return stringRedisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
                destinationKey, timeout, unit).toString();
    }

    
    public Long lRemove(String key, long index, String value) {
        return stringRedisTemplate.opsForList().remove(key, index, value);
    }

    
    public void lTrim(String key, long start, long end) {
        stringRedisTemplate.opsForList().trim(key, start, end);
    }

    
    public Long lSize(String key) {
        return stringRedisTemplate.opsForList().size(key);
    }
    //endregion

    
    //region set相关 *** 作

    
    public Long sAdd(String key, String... values) {
        return stringRedisTemplate.opsForSet().add(key, values);
    }
    

    
    public Long sAddCollection(String key, Collection list, String... values ) {
        if (list != null && list.size() > 0) {
            values=list.toArray(new String[list.size()]);
            return stringRedisTemplate.opsForSet().add(key,values);
        }
        return  0L;
    }



    
    public Long sRemove(String key, Object... values) {
        return stringRedisTemplate.opsForSet().remove(key, values);
    }

    
    public String sPop(String key) {
        return stringRedisTemplate.opsForSet().pop(key).toString();
    }

    
    public Boolean sMove(String key, String value, String destKey) {
        return stringRedisTemplate.opsForSet().move(key, value, destKey);
    }

    
    public Long sSize(String key) {
        return stringRedisTemplate.opsForSet().size(key);
    }

    
    public Boolean sIsMember(String key, Object value) {
        return stringRedisTemplate.opsForSet().isMember(key, value);
    }

    
    public Set sIntersect(String key, String otherKey) {
        return stringRedisTemplate.opsForSet().intersect(key, otherKey);
    }

    
    public Set sIntersect(String key, Collection otherKeys) {
        return stringRedisTemplate.opsForSet().intersect(key, otherKeys);
    }

    
    public Long sIntersectAndStore(String key, String otherKey, String destKey) {
        return stringRedisTemplate.opsForSet().intersectAndStore(key, otherKey,
                destKey);
    }

    
    public Long sIntersectAndStore(String key, Collection otherKeys,
                                   String destKey) {
        return stringRedisTemplate.opsForSet().intersectAndStore(key, otherKeys,
                destKey);
    }

    
    public Set sUnion(String key, String otherKeys) {
        return stringRedisTemplate.opsForSet().union(key, otherKeys);
    }

    
    public Set sUnion(String key, Collection otherKeys) {
        return stringRedisTemplate.opsForSet().union(key, otherKeys);
    }

    
    public Long sUnionAndStore(String key, String otherKey, String destKey) {
        return stringRedisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
    }

    
    public Long sUnionAndStore(String key, Collection otherKeys,
                               String destKey) {
        return stringRedisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
    }

    
    public Set sDifference(String key, String otherKey) {
        return stringRedisTemplate.opsForSet().difference(key, otherKey);
    }

    
    public Set sDifference(String key, Collection otherKeys) {
        return stringRedisTemplate.opsForSet().difference(key, otherKeys);
    }

    
    public Long sDifference(String key, String otherKey, String destKey) {
        return stringRedisTemplate.opsForSet().differenceAndStore(key, otherKey,
                destKey);
    }

    
    public Long sDifference(String key, Collection otherKeys,
                            String destKey) {
        return stringRedisTemplate.opsForSet().differenceAndStore(key, otherKeys,
                destKey);
    }

    
    public Set setMembers(String key) {
        return stringRedisTemplate.opsForSet().members(key);
    }

    
    public String sRandomMember(String key) {
        return stringRedisTemplate.opsForSet().randomMember(key).toString();
    }

    
    public List sRandomMembers(String key, long count) {
        return stringRedisTemplate.opsForSet().randomMembers(key, count);
    }

    
    public Set sDistinctRandomMembers(String key, long count) {
        return stringRedisTemplate.opsForSet().distinctRandomMembers(key, count);
    }

    
    public Cursor sScan(String key, ScanOptions options) {
        return stringRedisTemplate.opsForSet().scan(key, options);
    }
    //endregion

    
    //region zSet相关 *** 作

    
    public Boolean zAdd(String key, String value, double score) {
        return stringRedisTemplate.opsForZSet().add(key, value, score);
    }

    
    public Long zAdd(String key, Set> values) {
        return stringRedisTemplate.opsForZSet().add(key, values);
    }

    
    public Long zRemove(String key, Object... values) {
        return stringRedisTemplate.opsForZSet().remove(key, values);
    }

    
    public Double zIncrementScore(String key, String value, double delta) {
        return stringRedisTemplate.opsForZSet().incrementScore(key, value, delta);
    }

    
    public Long zRank(String key, Object value) {
        return stringRedisTemplate.opsForZSet().rank(key, value);
    }

    
    public Long zReverseRank(String key, Object value) {
        return stringRedisTemplate.opsForZSet().reverseRank(key, value);
    }

    
    public Set zRange(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().range(key, start, end);
    }

    
    public Set> zRangeWithScores(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().rangeWithScores(key, start, end);
    }

    
    public Set zRangeByScore(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().rangeByScore(key, min, max);
    }

    
    public Set> zRangeByScoreWithScores(String key,
                                                           double min, double max) {
        return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
    }

    
    public Set> zRangeByScoreWithScores(String key,
                                                           double min, double max, long start, long end) {
        return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
                start, end);
    }

    
    public Set zReverseRange(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
    }

    
    public Set> zReverseRangeWithScores(String key,
                                                           long start, long end) {
        return stringRedisTemplate.opsForZSet().reverseRangeWithScores(key, start,
                end);
    }

    
    public Set zReverseRangeByScore(String key, double min,
                                            double max) {
        return stringRedisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
    }

    
    public Set> zReverseRangeByScoreWithScores(
            String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
                min, max);
    }

    
    public Set zReverseRangeByScore(String key, double min,
                                            double max, long start, long end) {
        return stringRedisTemplate.opsForZSet().reverseRangeByScore(key, min, max,
                start, end);
    }

    
    public Long zCount(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().count(key, min, max);
    }

    
    public Long zSize(String key) {
        return stringRedisTemplate.opsForZSet().size(key);
    }

    
    public Long zZCard(String key) {
        return stringRedisTemplate.opsForZSet().zCard(key);
    }

    
    public Double zScore(String key, Object value) {
        Double score = stringRedisTemplate.opsForZSet().score(key, value);
        return score;
    }

    
    public Long zRemoveRange(String key, long start, long end) {
        return stringRedisTemplate.opsForZSet().removeRange(key, start, end);
    }

    
    public Long zRemoveRangeByScore(String key, double min, double max) {
        return stringRedisTemplate.opsForZSet().removeRangeByScore(key, min, max);
    }

    
    public Long zUnionAndStore(String key, String otherKey, String destKey) {
        return stringRedisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
    }

    
    public Long zUnionAndStore(String key, Collection otherKeys,
                               String destKey) {
        return stringRedisTemplate.opsForZSet()
                .unionAndStore(key, otherKeys, destKey);
    }

    
    public Long zIntersectAndStore(String key, String otherKey,
                                   String destKey) {
        return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKey,
                destKey);
    }

    
    public Long zIntersectAndStore(String key, Collection otherKeys,
                                   String destKey) {
        return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
                destKey);
    }

    
    public Cursor> zScan(String key, ScanOptions options) {
        return stringRedisTemplate.opsForZSet().scan(key, options);
    }

    //endregion

    //TODO------------------------------------------排序(正序、倒序)--------------------------------------------
    //region 排序(正序、倒序)

    
    public List pageAndSort(String key, Boolean sortDirection, Boolean paging , Integer currentPage, Integer pageNum) {
        List list = new ArrayList<>();
        currentPage = currentPage==null?0:currentPage-1;
        pageNum = pageNum==null?3:pageNum;
        sortDirection = sortDirection==null?true:sortDirection;
        paging = paging==null?false:paging;





        //根据分数内容进行正序或倒叙的List获取
        if (sortDirection){
//            linkedHashSet set = (linkedHashSet)stringRedisTemplate.opsForZSet().range(key, 0, -1);
            Set> tuples = stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key,0, 1000000, currentPage * pageNum, pageNum);
            List list_1 = new ArrayList<>(tuples);
            for (ZSetOperations.TypedTuple tup:tuples) {
                list_1.add(tup.getValue());
            }
            list.addAll(list_1);
//            stringRedisTemplate.opsForList().rightPushAll(tempListKey,list_1);
        }else {
//            linkedHashSet tuples = (linkedHashSet)stringRedisTemplate.opsForZSet().reverseRange(key, 0, -1);
            Set> tuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,0, 1000000, currentPage * pageNum, pageNum);
            List list_2 = new ArrayList<>();
            for (ZSetOperations.TypedTuple tup:tuples) {
                list_2.add(tup.getValue());
            }
            list.addAll(list_2);
//            stringRedisTemplate.opsForList().rightPushAll(tempListKey,list_2);
        }
//        list = stringRedisTemplate.opsForList().range(tempListKey,0,-1);

        //如果是进行分页排序
//        if (paging){
//            list = stringRedisTemplate.opsForList().range(tempListKey, currentPage * pageNum, (currentPage + 1) * pageNum-1);
//        }
//        stringRedisTemplate.delete(tempListKey);
        return list;
    }
    //endregion

    //TODO--------------------------------------------ZSet日常----------------------------------------------
    //region ZSet日常

    
    public Set dailyIntersectAndStore(String key, Collection otherKeys,
                                          String destKey) {
        stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKeys, destKey);
        return stringRedisTemplate.opsForZSet().range(destKey,0,-1);
    }


    
    public Set dailyUnionAndStore(String key, Collection otherKeys, String destKey) {
        stringRedisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey);
        return stringRedisTemplate.opsForZSet().range(destKey,0,-1);
    }

    
    public Set dailyDifference(String key, Collection otherKeys, String destKey) {

        stringRedisTemplate.delete("Temp:ZSet:diTemp1");
        stringRedisTemplate.delete("Temp:ZSet");
        ArrayList list = new ArrayList<>();
        Set diTemp1Set = dailyIntersectAndStore(key, list, "Temp:ZSet:diTemp1");
        for (int i = 0;i<=otherKeys.size();i++){
            stringRedisTemplate.opsForZSet().remove("Temp:ZSet:diTemp1",stringRedisTemplate.opsForZSet().range(otherKeys.toArray()[i].toString(),0,-1).toArray());
        }
        stringRedisTemplate.opsForZSet().unionAndStore("Temp:ZSet:diTemp1","Temp:ZSet",destKey);
        return stringRedisTemplate.opsForZSet().range(destKey,0,-1);
    }
    //endregion


}
 


package com.winshang.config;
 

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;


@Configuration
@EnableCaching
public class CacheRedisConfig extends RedisConfig {


    @Value("${spring.redis.database}")
    private int dbIndex;

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    
    @Primary
    @Bean(name ="cacheRedisFactory" )
    public RedisConnectionFactory cacheRedisConnectionFactory() {
        return createJedisConnectionFactory(dbIndex, host, port, password, timeout);
    }

    
    @Bean(name = "cacheRedisTemplate")
    public StringRedisTemplate cacheRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(cacheRedisConnectionFactory());
        setSerializer(stringRedisTemplate);
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }
}

package com.winshang.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;


@Configuration
@EnableCaching
public class DefaultRedisConfig extends RedisConfig {
    @Value("${spring.redis.database}")
    private int dbIndex;

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    
    @Bean(name ="defaultRedisFactory" )
    public JedisConnectionFactory defaultRedisConnectionFactory() {
        return createJedisConnectionFactory(dbIndex, host, port, password, timeout);
    }

    
    @Bean(name = "defaultRedisTemplate")
    public StringRedisTemplate defaultRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(defaultRedisConnectionFactory());
        setSerializer(stringRedisTemplate);
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }
}

package com.winshang.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;

@EnableCaching
@Configuration
public class RedisConfig {
    @Value("${spring.redis.pool.max-active}")
    private int redisPoolMaxActive;

    @Value("${spring.redis.pool.max-wait}")
    private int redisPoolMaxWait;

    @Value("${spring.redis.pool.max-idle}")
    private int redisPoolMaxIdle;

    @Value("${spring.redis.pool.min-idle}")
    private int redisPoolMinIdle;

    
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(o.getClass().getName())
                        .append(method.getName());
                for (Object object : objects) {
                    stringBuilder.append(object.toString());
                }
                return stringBuilder.toString();
            }
        };
    }

    
    public JedisConnectionFactory createJedisConnectionFactory(int dbIndex, String host, int port, String password, int timeout) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setDatabase(dbIndex);
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);
        jedisConnectionFactory.setPassword(password);
        jedisConnectionFactory.setTimeout(timeout);
        jedisConnectionFactory.setPoolConfig(setPoolConfig(redisPoolMaxIdle, redisPoolMinIdle, redisPoolMaxActive, redisPoolMaxWait, true));
        return jedisConnectionFactory;

    }

    
//    @Bean
//    public CacheManager cacheManager(StringRedisTemplate stringRedisTemplate) {
//        RedisCacheManager redisCacheManager = new RedisCacheManager(stringRedisTemplate);
//        return redisCacheManager;
//    }

    
    public JedisPoolConfig setPoolConfig(int maxIdle, int minIdle, int maxActive, int maxWait, boolean testOnBorrow) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxWaitMillis(maxWait);
        poolConfig.setTestonBorrow(testOnBorrow);
        return poolConfig;
    }

    
    public void setSerializer(StringRedisTemplate stringRedisTemplate) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //设置键(key)的序列化方式
        stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置值(value)的序列化方式
        stringRedisTemplate.setValueSerializer(new StringRedisSerializer());
        stringRedisTemplate.setHashKeySerializer(new StringRedisSerializer());
        stringRedisTemplate.setHashValueSerializer(new StringRedisSerializer());
        stringRedisTemplate.afterPropertiesSet();
    }
}

@Autowired
private RedisUtil redisUtil;

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5707364.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)