欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring-data-redis实战

程序员文章站 2022-06-16 15:46:08
...

    

redis 学习问题总结

http://aperise.iteye.com/blog/2310639

ehcache memcached redis 缓存技术总结

http://aperise.iteye.com/blog/2296219

redis-stat 离线安装

http://aperise.iteye.com/blog/2310254

redis  cluster 非ruby方式启动

http://aperise.iteye.com/blog/2310254

redis-sentinel安装部署

http://aperise.iteye.com/blog/2342693

spring-data-redis使用

 http://aperise.iteye.com/blog/2342615

redis客户端redisson实战

http://blog.csdn.net/zilong_zilong/article/details/78252037

redisson-2.10.4源代码分析

http://blog.csdn.net/zilong_zilong/article/details/78609423

tcmalloc jemalloc libc选择

http://blog.csdn.net/u010994304/article/details/49906819

 spring-data-redis实战

    spring-data-redis版本1.4.0.RELEASE之后引入了sentinel;

    spring-data-redis版本1.4.0.RELEASE之后对于spring的依赖版本>=4.0.7.RELEASE;

 

    spring-data-redis版本1.4.0.RELEASE之前不支持sentinel;

    spring-data-redis版本1.4.0.RELEASE之前对于spring的依赖版本<=3.2.10.RELEASE;

 

    jedis-2.8不支持Redis-cluster部署方式中集群设置密码访问;

    jedis-2.9开始支持redis-cluster部署方式中集群设置密码访问;

 

    spring-data-redis版本1.7.x不支持redis-cluster部署方式集群设置密码访问;

    spring-data-redis版本1.8.x开始支持redis-cluster部署方式集群设置密码访问;

 

1.为什么选择spring-data-redis?

    spring-data-redis已经对jedis、jredis进行了封装,完美兼容redis sentinel部署模式、兼容redis-cluster部署模式、单节点redis部署模式,提供统一的API(RedisTemplate)来调用不同的部署模式,完全不用担心redis部署模式变化导致redis客户端代码做调整

 

    1)单节点部署模式

    单节点部署模式时与spring、spring-data-redis集成文件如下:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"
	default-lazy-init="true">

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="2048" />
		<property name="maxIdle" value="200" />
		<property name="numTestsPerEvictionRun" value="1024" />
		<property name="timeBetweenEvictionRunsMillis" value="30000" />
		<property name="minEvictableIdleTimeMillis" value="-1" />
		<property name="softMinEvictableIdleTimeMillis" value="10000" />
		<property name="maxWaitMillis" value="1500" />
		<property name="testOnBorrow" value="true" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnReturn" value="false" />
		<property name="jmxEnabled" value="true" />
		<property name="blockWhenExhausted" value="false" />
	</bean>

	<!-- 只有一个节点的redis集群 -->
	<bean id="oneNodeJedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:host-name="192.168.29.24" p:port="6379" p:pool-config-ref="jedisPoolConfig" />
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
		<property name="connectionFactory" ref="oneNodeJedisConnectionFactory" />
		<property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="valueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="hashKeySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="hashValueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
	</bean>
</beans>

 

    2)sentinel部署模式

    sentinel部署模式时与spring、spring-data-redis集成文件如下:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"
	default-lazy-init="true">

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="2048" />
		<property name="maxIdle" value="200" />
		<property name="numTestsPerEvictionRun" value="1024" />
		<property name="timeBetweenEvictionRunsMillis" value="30000" />
		<property name="minEvictableIdleTimeMillis" value="-1" />
		<property name="softMinEvictableIdleTimeMillis" value="10000" />
		<property name="maxWaitMillis" value="1500" />
		<property name="testOnBorrow" value="true" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnReturn" value="false" />
		<property name="jmxEnabled" value="true" />
		<property name="blockWhenExhausted" value="false" />
	</bean>

	<!-- 采用sentinel模式的redis -->
	<bean id="redisSentinelConfiguration"
		class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
		<property name="master">
			<bean class="org.springframework.data.redis.connection.RedisNode">
				<property name="name" value="redis-sentinel" />
			</bean>
		</property>
		<property name="sentinels">
			<set>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="192.168.173.23" />
					<constructor-arg name="port" value="26382" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="192.168.173.24" />
					<constructor-arg name="port" value="26382" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode ">
					<constructor-arg name="host" value="192.168.173.25" />
					<constructor-arg name="port" value="26382" />
				</bean>
			</set>
		</property>
	</bean>
	<bean id="sentinelJedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:password="abcd_123456" p:pool-config-ref="jedisPoolConfig">
		<constructor-arg name="sentinelConfig" ref="redisSentinelConfiguration"></constructor-arg>
	</bean>
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
		<property name="connectionFactory" ref="sentinelJedisConnectionFactory" />
		<property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="valueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="hashKeySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="hashValueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
	</bean>
</beans>

        注意:上面IP和端口只需配置sentinel节点的IP和端口,sentinel采用投票方式进行故障切换,而投票方式下原则是少数服从多数,所以sentinel一般至少是3台,上面是我部署的3台sentinel节点的IP和端口。

 

    3)redis-cluster部署模式

    redis-cluster部署模式时与spring、spring-data-redis集成文件如下:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"
	default-lazy-init="true">

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="2048" />
		<property name="maxIdle" value="200" />
		<property name="numTestsPerEvictionRun" value="1024" />
		<property name="timeBetweenEvictionRunsMillis" value="30000" />
		<property name="minEvictableIdleTimeMillis" value="-1" />
		<property name="softMinEvictableIdleTimeMillis" value="10000" />
		<property name="maxWaitMillis" value="1500" />
		<property name="testOnBorrow" value="true" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnReturn" value="false" />
		<property name="jmxEnabled" value="true" />
		<property name="blockWhenExhausted" value="false" />
	</bean>

	<!-- 采用redis-cluster的redis -->
	<bean id="redisClusterConfiguration" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
		<property name="maxRedirects" value="3" />
		<property name="clusterNodes">
			<set>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="192.168.173.23" />
					<constructor-arg name="port" value="6379" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="192.168.173.23" />
					<constructor-arg name="port" value="6380" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode ">
					<constructor-arg name="host" value="192.168.173.23" />
					<constructor-arg name="port" value="6381" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="192.168.173.24" />
					<constructor-arg name="port" value="6379" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode">
					<constructor-arg name="host" value="192.168.173.24" />
					<constructor-arg name="port" value="6380" />
				</bean>
				<bean class="org.springframework.data.redis.connection.RedisNode ">
					<constructor-arg name="host" value="192.168.173.24" />
					<constructor-arg name="port" value="6381" />
				</bean>
			</set>
		</property>
	</bean>
	<bean id="clusterJedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:pool-config-ref="jedisPoolConfig">
		<constructor-arg name="clusterConfig" ref="redisClusterConfiguration" />
	</bean>
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="clusterJedisConnectionFactory" />
		<property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="valueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="hashKeySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
		<property name="hashValueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/></property>
	</bean>
</beans>

 

2.使用spring-data-redis时比较纠结的与jedis整合版本问题

    spring-data-redis版本1.4.0.RELEASE之后引入了sentinel;

    spring-data-redis版本1.4.0.RELEASE之后对于spring的依赖版本>=4.0.7.RELEASE;

 

    spring-data-redis版本1.4.0.RELEASE之前不支持sentinel;

    spring-data-redis版本1.4.0.RELEASE之前对于spring的依赖版本<=3.2.10.RELEASE;

 

    这个没啥好纠结的,使用什么版本的spring-data-redis就查询这个版本使用的jedis,一种比较靠谱的查询方法是登录http://search.maven.org/ 进行查询,如下:


spring-data-redis实战
            
    
    博客分类: 缓存redis spring-data-redis
     这里我使用的是最新的1.7.5.RELEASE版本,点击上图pom链接进去搜索jedis,即可查看到jedis版本,如下:
spring-data-redis实战
            
    
    博客分类: 缓存redis spring-data-redis
     所以最后我的maven依赖如下:

		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.7.5.RELEASE</version>
		</dependency>

 

3.报错Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: 

Invocation of init method failed; nested exception is java.lang.NoSuchMethodError:
org.springframework.core.serializer.support.DeserializingConverter.<init>(Ljava/lang/ClassLoader;)V
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:272)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 37 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.data.redis.core.RedisTemplate com.besttone.signal.service.redis.RedisService.redisTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in class path resource [spring-redis.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.serializer.support.DeserializingConverter.<init>(Ljava/lang/ClassLoader;)V
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 50 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in class path resource [spring-redis.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.serializer.support.DeserializingConverter.<init>(Ljava/lang/ClassLoader;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1127)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 52 more
Caused by: java.lang.NoSuchMethodError: org.springframework.core.serializer.support.DeserializingConverter.<init>(Ljava/lang/ClassLoader;)V
at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.<init>(JdkSerializationRedisSerializer.java:53)
at org.springframework.data.redis.core.RedisTemplate.afterPropertiesSet(RedisTemplate.java:119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 62 more
[ERROR] http-bio-9045-exec-4 2016-12-02 22:24:09,479 org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'interfaceController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.besttone.signal.service.redis.RedisService com.besttone.web.controller.InterfaceController.redisService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.data.redis.core.RedisTemplate com.besttone.signal.service.redis.RedisService.redisTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in class path resource [spring-redis.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.serializer.support.DeserializingConverter.<init>(Ljava/lang/ClassLoader;)V
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)

     上面问题主要解决办法是将spring版本升级,之前我用的spring版本是4.1.6.RELEASE,将其版本升级到4.3.34.RELEASE后问题解决,而不是网上所说的将jedis版本降级到2.6.2

 

4.RedisService.java实现类

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.util.SafeEncoder;
@Component
public class RedisService {
    private static Logger logger = Logger.getLogger(RedisService.class);
    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate;
    
    /**
     * redis中key对应的值增加数值integer
     * @param key 
     * @param incrValue
     * @return
     */
	public Long incrBy(final String key, final long incrValue){
    	//将key对应的数字加decrement。如果key不存在,操作之前,key就会被置为0。
    	//如果key的value类型错误或者是个不能表示成数字的字符串,
    	//就返回错误。这个操作最多支持64位有符号的正型数字。
		return (Long) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.incrBy(SafeEncoder.encode(key), incrValue);
			}
		});
    }
    
    /**
     * 判断redis中该key是否存在
     * @param key
     * @return
     */
	public Boolean exists(final String key) {
		return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.exists(SafeEncoder.encode(key));
			}
		});
    }
    
    /**
     * 设置某个key过期时间
     * @param key
     * @param seconds
     * @return
     */
	public Boolean expire(final String key, final int seconds) {
    	//Integer reply, specifically: 
    	//1: the timeout was set. 
    	//0: the timeout was not set since the key already has an associated timeout (this may happen only in Redis versions < 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist.
		return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.expire(SafeEncoder.encode(key), seconds);
			}
		});
    }
    
    /**
     * 获取key对应的值
     * @param key
     * @return
     */
	public String get(final String key) {
		return (String) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public String doInRedis(RedisConnection connection) throws DataAccessException {
				byte[] keyBytes = SafeEncoder.encode(key);
				byte[] valueBytes = connection.get(keyBytes);
					if (null != valueBytes)
						return SafeEncoder.encode(valueBytes);
				return null;
			}
		});
	}
    
    /**
     * 获取key对应的值
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public Set<String> smembers(final String key) {
    	return (Set<String>) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
				Set<String> returnSet = new HashSet<String>();
				byte[] keyBytes = SafeEncoder.encode(key);
				Set<byte[]> bytesSet = connection.sMembers(keyBytes);
					if(null!=bytesSet&&bytesSet.size()>0){
						for(byte[] bytes : bytesSet){
							returnSet.add(SafeEncoder.encode(bytes));
						}
					}
				return returnSet;
			}
    	});
    } 
    
    /**
     * 获取key对应的值
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> hgetAll(final String key) {
		return (Map<String, String>) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Map<String, String> doInRedis(RedisConnection connection) throws DataAccessException {
				Map<String, String> returnMap = new HashMap<String, String>();
				byte[] keyBytes = SafeEncoder.encode(key);
					Map<byte[], byte[]> bytesMap = connection.hGetAll(keyBytes);
					if (null != bytesMap && bytesMap.size() > 0) {
						for (Map.Entry<byte[], byte[]> entry : bytesMap.entrySet()) {
							returnMap.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue()));
						}
					}
				return returnMap;
			}
		});
    } 

	public Boolean hmset(final String key, final Map<String, String> hash) {
		return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				try {
				    final Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(hash.size());
				    for (final Entry<String, String> entry : hash.entrySet()) {
				      bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue()));
				    }
				    connection.hMSet(SafeEncoder.encode(key), bhash);
					return true;
				} catch (Exception e) {
					logger.error("error in RedisService.hmset(final String key, final Map<String, String> hash)", e);
					return false;
				}
			}
		});
	}

	public Long srem(final String key, final String... members) {
		return (Long) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.sRem(SafeEncoder.encode(key), SafeEncoder.encodeMany(members));
			}
		});
    }
	public Long sadd(final String key, final String... members) {
		return (Long) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.sAdd(SafeEncoder.encode(key), SafeEncoder.encodeMany(members));
			}
		});
    }
	public Long del(final String key) {
		return (Long) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.del(SafeEncoder.encodeMany(key));
			}
		});
    }
	public Boolean set(final String key, final String value) {
		return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				try {
					connection.set(SafeEncoder.encode(key), SafeEncoder.encode(value));
					return true;
				} catch (Exception e) {
					logger.error("error in RedisService.set(final String key, final String value)", e);
					return false;
				}
			}
		});
    }
}

 

  • spring-data-redis实战
            
    
    博客分类: 缓存redis spring-data-redis
  • 大小: 36.6 KB
  • spring-data-redis实战
            
    
    博客分类: 缓存redis spring-data-redis
  • 大小: 53.7 KB
相关标签: spring-data-redis