打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Spring Data Redis 单节点和集群配置和RedisTemplate用法

标签(空格分隔): Spring-Data


使用SpringData更加方便我们对关系型数据库和非关系型数据库更好的操作,封装了通用的代码,使得操作更加快捷简单。

一、Spring Data Redis的配置

引入相关jar包,注意依赖和冲突问题。maven 引入pom.xml:
  • 1
  • 2
  • 3
<dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>    </dependency>    <!--spring-data-redis相关,会自动引入相关jar-->    <dependency>      <groupId>org.springframework.data</groupId>      <artifactId>spring-data-redis</artifactId>      <version>1.7.4.RELEASE</version>    </dependency>    <!--spring测试相关-->    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-test</artifactId>      <version>4.2.8.RELEASE</version>    </dependency>    <!--redis相关-->    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->    <dependency>      <groupId>redis.clients</groupId>      <artifactId>jedis</artifactId>      <version>2.9.0</version>    </dependency>  </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

手动添加jar包 相关jar下载地址

配置文件

可以使用引入外部文件的方式也可以通过在xml文件中配置的方式
  • 1
  • 2

单节点配置方式

properties文件

#JedisPoolConfig的参数#最大连接数redis.pool.maxTotal=30#最大空闲时间redis.pool.maxIdle=10#每次最大连接数redis.pool.numTestsPerEvictionRun=1024#释放扫描的扫描间隔redis.pool.timeBetweenEvictionRunsMillis=30000#连接的最小空闲时间redis.pool.minEvictableIdleTimeMillis=1800000#连接控歘按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放redis.pool.softMinEvictableIdleTimeMillis=10000#获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1redis.pool.maxWaitMillis=1500#在获得链接的时候检查有效性,默认falseredis.pool.testOnBorrow=true#在空闲时检查有效性,默认falseredis.pool.testWhileIdle=true#连接耗尽时是否阻塞,false报异常,true阻塞超时,默认trueredis.pool.blockWhenExhausted=false#JedisConnectionFactory的参数#主机地址,默认:localhostredis.hostName=192.168.200.128#主机端口,默认:6379redis.port=6379#超时时间,默认:2000redis.timeout=3000#密码#redis.password#是否使用连接池,默认trueredis.usePool=true#使用数据库的索引,0-15之间的数字,默认:0redis.dbIndex=0#是否使用数据类型的转换,默认:true#redis.convertPipelineAndTxResults#哨兵配置#redis.sentinelConfig#集群配置#redis.clusterConfig
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

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"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <!--引入配置文件-->    <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="order" value="1"/>        <property name="ignoreUnresolvablePlaceholders" value="true"/>        <property name="locations">            <list>                <value>classpath:redis.properties</value>            </list>        </property>    </bean>    <!--配置 jedis pool-->    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <!-- 最大连接数 -->        <property name="maxTotal" value="${redis.pool.maxTotal}"/>        <!-- 最大空闲时间 -->        <property name="maxIdle" value="${redis.pool.maxIdle}"/>        <!-- 每次最大连接数 -->        <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"/>        <!-- 释放扫描的扫描间隔 -->        <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>        <!-- 连接的最小空闲时间 -->        <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"/>        <!-- 连接控歘按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放 -->        <property name="softMinEvictableIdleTimeMillis" value="${redis.pool.softMinEvictableIdleTimeMillis}"/>        <!-- 获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1 -->        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>        <!-- 在获得链接的时候检查有效性,默认false -->        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>        <!-- 在空闲时检查有效性,默认false -->        <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/>        <!-- 连接耗尽时是否阻塞,false报异常,true阻塞超时 默认:true-->        <property name="blockWhenExhausted" value="${redis.pool.blockWhenExhausted}"/>    </bean>    <!--spring data redis -->    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        <property name="hostName" value="${redis.hostName}"/>        <property name="port" value="${redis.port}"/>        <property name="timeout" value="${redis.timeout}"/>        <property name="database" value="${redis.dbIndex}"/>        <property name="usePool" value="${redis.usePool}"/>        <!--可以通过构造注入或者Set注入两种方式-->        <property name="poolConfig" ref="jedisPoolConfig"/>    </bean>    <!--redisTemplate-->    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory"/>    </bean></beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

集群配置方式
properties文件

#JedisPoolConfig的参数#最大连接数redis.pool.maxTotal=30#最大空闲时间redis.pool.maxIdle=10#每次最大连接数redis.pool.numTestsPerEvictionRun=1024#释放扫描的扫描间隔redis.pool.timeBetweenEvictionRunsMillis=30000#连接的最小空闲时间redis.pool.minEvictableIdleTimeMillis=1800000#连接控歘按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放redis.pool.softMinEvictableIdleTimeMillis=10000#获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1redis.pool.maxWaitMillis=1500#在获得链接的时候检查有效性,默认falseredis.pool.testOnBorrow=true#在空闲时检查有效性,默认falseredis.pool.testWhileIdle=true#连接耗尽时是否阻塞,false报异常,true阻塞超时,默认trueredis.pool.blockWhenExhausted=false#RedisClusterConfiguration配置redis.maxRedirects=5#主机和端口号redis.host1=192.168.200.128redis.port1=7000redis.host2=192.168.200.128redis.port2=7001redis.host3=192.168.200.128redis.port3=7002redis.host4=192.168.200.128redis.port4=7003redis.host5=192.168.200.128redis.port5=7004redis.host6=192.168.200.128redis.port6=7005
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

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"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <!--引入配置文件-->    <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="order" value="1"/>        <property name="ignoreUnresolvablePlaceholders" value="true"/>        <property name="locations">            <list>                <value>classpath:redis-cluster.properties</value>            </list>        </property>    </bean>    <!--配置 jedis pool-->    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <!-- 最大连接数 -->        <property name="maxTotal" value="${redis.pool.maxTotal}"/>        <!-- 最大空闲时间 -->        <property name="maxIdle" value="${redis.pool.maxIdle}"/>        <!-- 每次最大连接数 -->        <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"/>        <!-- 释放扫描的扫描间隔 -->        <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>        <!-- 连接的最小空闲时间 -->        <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"/>        <!-- 连接控歘按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放 -->        <property name="softMinEvictableIdleTimeMillis" value="${redis.pool.softMinEvictableIdleTimeMillis}"/>        <!-- 获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1 -->        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>        <!-- 在获得链接的时候检查有效性,默认false -->        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>        <!-- 在空闲时检查有效性,默认false -->        <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/>        <!-- 连接耗尽时是否阻塞,false报异常,true阻塞超时 默认:true-->        <property name="blockWhenExhausted" value="${redis.pool.blockWhenExhausted}"/>    </bean>    <!--配置RedisClusterConfiguration-->    <bean id="redisClusterConfiguration" class="org.springframework.data.redis.connection.RedisClusterConfiguration">        <property name="maxRedirects" value="${redis.maxRedirects}"></property>        <property name="clusterNodes">            <set>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg name="host" value="${redis.host1}"/>                    <constructor-arg name="port" value="${redis.port1}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg name="host" value="${redis.host2}"/>                    <constructor-arg name="port" value="${redis.port2}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg name="host" value="${redis.host3}"/>                    <constructor-arg name="port" value="${redis.port3}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg name="host" value="${redis.host4}"/>                    <constructor-arg name="port" value="${redis.port4}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg name="host" value="${redis.host5}"/>                    <constructor-arg name="port" value="${redis.port5}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg name="host" value="${redis.host6}"/>                    <constructor-arg name="port" value="${redis.port6}"/>                </bean>            </set>        </property>    </bean>    <!--配置JedisConnectionFactory-->    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        <constructor-arg name="poolConfig" ref="jedisPoolConfig"/>        <constructor-arg name="clusterConfig" ref="redisClusterConfiguration"/>    </bean>    <!--redisTemplate-->    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory"/>    </bean></beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

二、RedisTemplate的用法

  1. Operations

        opsForXXX和boundXXXOps的区别?XXX为Value的类型,前者获取一个operator,但是没有指定操作的对象(key),可以在一个连接(事务)内操作多个key以及对应的value;后者获取了一个指定的对象(key)的operator,在一个连接(事务)内只能操作这个对应的key。    关于计数API(increment)中有个小问题需要注意,通过increment计数后,通过get方式获取计数值的时候可能会抛出EOF异常(和本地的jdk以及redis的编译版本有关),可以考虑使用boundValueOps(key).get(0,-1)获得计数值。
    • 1
    • 2
    • 3
    • 4
  2. ValueOperations和BoundValueOperations

    ValueOperations operations = redisTemplate.opsForValue();        String key = "XXX";        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(key);
    • 1
    • 2
    • 3
    类:ValueOperations可以理解为:Map<Object,Object>方法:set(key,value)保存      get(key)获取类:BoundValueOperations可以理解为,预先设置好了Key,可以对此key进行其他操作,如设置value,修改value,获得value等
    • 1
    • 2
    • 3
    • 4
    • 5

    简单示例:

    ValueOperations operations = redisTemplate.opsForValue();String key = "name";//存入key-valueoperations.set("name","zhangsan");//根据key取出ValueObject name = operations.get("name");System.out.println("name:"+name);//追加operations.append("name","is man");//获得并修改operations.getAndSet("name","zhangsan-1");Object name1 = operations.get("name");System.out.println("修改后:"+name1);String key = "name-1";BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(key);//和ValueOperations类似
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  3. ListOperations 和 BoundListOperations

     ListOperations listOperations = redisTemplate.opsForList();    String key = "springData";    BoundListOperations boundListOperations = redisTemplate.boundListOps(key);
    • 1
    • 2
    • 3
    类:ListOperations可以理解为:List<Object>BoundListOperations可以理解为,预先设置好了Key,可以对此key进行其他操作,如设置value,修改value,获得value等
    • 1
    • 2
    • 3

    简单示例:

    ListOperations listOperations = redisTemplate.opsForList();//push键值对listOperations.leftPush(key,"aaa");listOperations.leftPush(key,"bbb");listOperations.index(1,1000);//pop值Object leftPop = listOperations.leftPop(key);System.out.println(leftPop);listOperations.set(key,100,"测试数据");//ListOperations可以设置泛型ListOperations<String,Integer> listOperations1 = redisTemplate.opsForList();String key = "springData";BoundListOperations boundListOperations = redisTemplate.boundListOps(key);//和ListOperations类似
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
  4. SetOperations 和 BoundSetOperations

    SetOperations setOperations = redisTemplate.opsForSet();    String key = "springData";    BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(key);
    • 1
    • 2
    • 3
    类:SetOperations可以理解为:Set<Object>BoundSetOperations可以理解为,预先设置好了Key,可以对此key进行其他操作,如设置value,修改value,获得value等
    • 1
    • 2
    • 3

    简单示例和解释:

    /** * Set集合,类似于 * *  Map<Object, Set<Object>> map = new HashMap<Object, Set<Object>>(); *  Set<Object> set = new HashSet<Object>(); */@Testpublic void test04(){    SetOperations setOperations = redisTemplate.opsForSet();    /**     * 添加,类似于     *     *  Map<Object, Set<Object>> map = new HashMap<Object, Set<Object>>();     *  Set<Object> set = new HashSet<Object>();     *  map.put(key,set);     *  Set<Object> set = map.get(key);     *  set.add(value);     */    setOperations.add("springData","redis");    //获取    Set springData = setOperations.members("springData");    //获取两个key的value(Set)交集    setOperations.intersect("springData","SpringData1");    //获取两个key的value(Set)补集    setOperations.difference("springData","SpringData1");    //获取两个key的value(Set)并集    setOperations.union("springData","SpringData1");    String key = "springData";    BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(key);    //和SetOperations操作类似}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  5. ZSetOperations 和 BoundZSetOperations

    ZSetOperations zSetOperations = redisTemplate.opsForZSet();    String key = "springData";    BoundZSetOperations boundZSetOperations = redisTemplate.boundZSetOps(key);
    • 1
    • 2
    • 3
    类:SetOperations可以理解为:Set<Object>        BoundSetOperations可以理解为,预先设置好了Key,可以对此key进行其他操作,如设置value,修改value,获得value等
    • 1
    • 2
    • 3
  6. HashOperations 和 BoundHashOperations

        HashOperations hashOperations = redisTemplate.opsForHash();    String key = "springData";    BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(key);
    • 1
    • 2
    • 3

    说明:APi中的方法很多,大家可以自行测试。源码下载 【源码下载连接

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Spring Boot 操作 Redis,三种方案全解析!
SpringBoot Redis缓存
淘宝购物车是如何使用Spring Boot Redis 扛住十万qps重复提交的(含代码实例)
redis自学-redis工具类
Spring Cache缓存原理与Redis实践
SpringBoot集成Redis用法笔记
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服