spring 4.0.3 整合spring-data-redis jedis

近来项目需要redis作为缓存系统,爬了好多坑,特此纪念

首先  pom.xml

<!--整合Redis-->
<!--需要注意导入依赖的版本一定要匹配-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.4.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.6.2</version>
</dependency>

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!-- scanner redis properties  -->
    <context:property-placeholder location="classpath:config.properties"/>

    <!--(1)如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"-->
    <!--(2)注意新版的(具体从哪个版本开始不清楚,有兴趣可以查一下)JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码。-->
    <!-- redis连接池 -->
    <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxActive}"></property>
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <property name="maxWaitMillis" value="${redis.maxWait}"></property>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
    </bean>
    <!-- redis连接工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"></property>
        <property name="port" value="${redis.port}"></property>
        <property name="password" value="${redis.pass}"></property>
        <property name="poolConfig" ref="jedisConfig"></property>
    </bean>
    <!-- redis操作模板,这里采用尽量面向对象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>
</beans>

config.properties


#redis绑定的主机地址
redis.host=127.0.0.1
#redis监听端口,默认6379
redis.port=6379
#redis授权密码
redis.pass=
#最大空闲数,空闲链接数大于maxIdle时,将进行回收
redis.maxIdle=100
#最大连接数,能够同时建立的“最大链接个数”
redis.maxActive=300
#最大等待时间:单位ms
redis.maxWait=1000
#使用连接时,检测连接是否成功
redis.testOnBorrow=true
#当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
redis.timeout=10000

RedisUtil.java

只做了简单的方法  string和list

public class RedisUtil {
    //https://blog.csdn.net/javaxiaibai0414/article/details/88666453
    private static RedisUtil redisUtil = new RedisUtil();
    private static RedisTemplate client = null;			//连接池自动管理,提供了一个高度封装的“RedisTemplate”类
    private static synchronized RedisTemplate getRedisUtil() {
        if(client == null){
            client = SpringContextHolder.getBean("redisTemplate");
        }
        return client;
    }

    private RedisUtil() {}
    /**
     * 获取唯一实例.
     * @return
     */
    public static RedisUtil getInstance() {
        if(redisUtil == null){
            synchronized (RedisUtil.class) {
                redisUtil = new RedisUtil();
            }
        }
        return redisUtil;
    }


    //-------------------------------------------------
    //------------------通用操作工具方法----------------
    /**
     * 指定缓存失效时间
     * @param key
     * @param time 时间 秒
     * @return
     */
    public boolean expire(String key,long time){
        try{
            if(time>0){
                getRedisUtil().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 getRedisUtil().getExpire(key);
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try{
            return getRedisUtil().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) {
                getRedisUtil().delete(key[0]);
            }else {
                getRedisUtil().delete(CollectionUtils.arrayToList(key));
            }
        }
    }


    //-------------------------------------------------
    //------------------String类型相关操作方法----------


    /**
     * 获取缓存
     * @param key
     * @return
     */
    public Object get(String key) {
        return key==null?null:getRedisUtil().opsForValue().get(key);
    }

    /**
     * 设置缓存  不设置过期时间(默认永久有效)
     * @param key
     * @param value
     * @return T成功 F失败
     */
    public boolean set(String key ,String value) {
        try{
            getRedisUtil().opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存并设置过期时间 --一般用于token
     * @param key
     * @param value
     * @param time time要大于0 反之则设置为无限期
     * @return
     */
    public boolean set(String key,String value,long time){
        try {
            if (time>0){
                getRedisUtil().opsForValue().set(key,value,time,TimeUnit.SECONDS);
            }else {
                set(key,value);
            }

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     * @param key
     * @param delta
     * @return
     */
    public long incr(String key,long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return getRedisUtil().opsForValue().increment(key,delta);
    }

    /**
     * 递减
     * @param key
     * @param delta
     * @return
     */
    public long decr(String key,long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return getRedisUtil().opsForValue().increment(key,-delta);
    }

    //-------------------------------------------------
    //------------------LIST类型相关操作方法------------


    /**
     * 获取list缓存的内容
     * @param key
     * @param start 开始
     * @param end 结束 0到-1代表返回所有
     * @return
     */
    public List<Object> lGet(String key,long start,long end){
        try{
            return getRedisUtil().opsForList().range(key,start,end);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key
     * @return
     */
    public long lGetListSize(String key){
        try {
            return getRedisUtil().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 getRedisUtil().opsForList().index(key,index);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 将list放入缓存  永久有效
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, Object value){
        try {
            getRedisUtil().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 {
            getRedisUtil().opsForList().rightPush(key,value);
            if (time>0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list放入缓存  永久有效
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, List<Object> value){
        try {
            getRedisUtil().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 {
            getRedisUtil().opsForList().rightPushAll(key,value);
            if (time>0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }



}

后记:一定要注意spring-data-redis 和 jedis的版本(这里使用的spring-data-redis 1.4.2和jedis 2.62),这俩货的版本要求太严格了,我项目还是使用spring4 ,本来想升级5结果错误太多放弃了,升级spring5后应该版本问题会好很多

感谢:https://www.cnblogs.com/hjwublog/p/5749929.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值