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/ 进行查询,如下:
这里我使用的是最新的1.7.5.RELEASE版本,点击上图pom链接进去搜索jedis,即可查看到jedis版本,如下:
所以最后我的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:
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实战详解》 在现代Web应用中,数据的高效存储和访问是至关重要的。Spring Data Redis作为Spring框架的一部分,为开发者提供了强大的Redis支持,使得我们可以充分利用Redis的高性能特性,实现...
在Spring Boot中,我们可以通过引入`spring-boot-starter-data-redis`依赖来启用Redis支持。但是,要配置Redis集群,通常需要设置多个节点地址、密码、端口等信息。在Spring Boot 2.1及以上版本中,我们可以利用`...
《深入浅出Spring Data Redis:连接池与事务实践》 Spring Data Redis是Spring框架的一个重要模块,它为Redis提供了丰富的支持,使得在Java应用中使用Redis变得更加便捷。本篇文章将详细探讨Spring Data Redis的...
4. **集成Spring Data Redis**:Spring Data Redis项目提供了更高级别的操作,如Repository支持,允许开发者通过接口定义CRUD操作。 ```java public interface MyRepository extends CrudRepository, String> { //...
《Spring Data Redis实战详解》 在当今的软件开发领域,数据存储和检索是核心环节,而Redis作为一种高性能的键值数据库,因其高速读写、丰富的数据结构以及支持主从复制和事务等特性,被广泛应用于缓存、消息队列、...
《Spring Data Redis 深入解析与实战指南》 在当今大数据时代,Redis作为一个高性能的键值数据库,因其高效的数据处理能力以及丰富的数据结构而备受青睐。Spring Data Redis是Spring框架的一部分,它为Redis提供了...
在Spring项目中,首先需要在pom.xml或build.gradle文件中引入Spring Data Redis和Jedis(或Lettuce)客户端库的依赖。例如,对于Maven项目: ```xml <groupId>org.springframework.boot <artifactId>spring-boot...
综上所述,"TS-R-2-2024-spring-data.zip"可能包含Spring Data的相关教程、实战案例、代码样本,或者是一整个使用Spring Data构建的应用程序。学习这些内容将有助于提升开发者在数据访问和管理方面的技能,适应不断...
"spring-data-redis"库提供了Spring Data Redis模块,它简化了与Redis的交互,使开发者可以方便地将session数据持久化到Redis。通过使用Redis,你可以实现跨多个服务器的session共享,并利用其高可用性和可扩展性。 ...
在本篇《Spring Boot 实战 - Redis》中,我们将深入探讨如何在Spring Boot框架中集成并使用Redis作为数据缓存,提升应用性能。Redis是一个开源的、基于内存的数据结构存储系统,可作为数据库、缓存和消息代理。...
SpringDataRedis是一个强大的Java库,它是Spring Data项目的一部分,专门设计用于简化与Redis数据库的交互。Redis是一个开源的、高性能的键值存储系统,常用于数据缓存、消息队列和分布式服务协调等场景。SpringData...
Spring Boot可以通过`spring-boot-starter-data-redis`起步依赖集成Redis,利用其高并发、低延迟特性提升系统性能。 7. **定时任务(Schedule)**: Spring Boot提供了`@Scheduled`注解来创建定时任务,配合`...
在本案例实战中,我们将探讨如何使用Spring Boot与Redis的GEO(Geospatial)功能来实现一个查找附近门店的功能。Spring Boot是一个流行的Java框架,它简化了设置和配置Spring应用的过程,而Redis则是一个高性能的...
data-redis|[lettuce,redis,session redis,YAML配置,连接池,对象存储](https://github.com/smltq/spring-boot-demo/blob/master/data-redis/HELP.md) quartz|[Spring Scheduler,Quartz,分布式调度,集群,mysql持久化...
使用spring-jms 负载均衡:nginx 搜索:solr集群(solrCloud),配合zookeeper搭建, 使用spring-data-solor 缓存:redis集群,使用spring-data-redis 图片存储:fastDFS集群 网页静态化:freemarker 单点登录:cas ...
在本案例实战中,我们将探讨如何使用Spring Boot与Redis集成,以实现缓存分页数据查询,提升应用程序的性能和响应速度。Spring Boot是Java领域一个流行的微服务框架,它简化了Spring应用的初始搭建以及开发过程。而...
SpringData Redis提供了一套丰富的API,如StringTemplate、HashTemplate等,便于我们在业务代码中操作Redis。 五、SpringBoot、MyBatis与Redis整合实战 在实际项目中,我们常常会结合这三大技术进行数据处理。例如...
Spring Data Redis是Spring框架的一个模块,它为Redis提供了丰富的支持,包括连接池管理、命令操作接口、数据类型映射以及模板模式。Spring Boot通过自动配置,可以轻松地连接到Redis服务器,只需在`application....
SSM(Spring、SpringMVC...<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <!-- 其他配置如password、database等根据实际情况添加 --> ...
本项目“项目整合redis实战”旨在提供一个实际操作的教程,教你如何将Redis集成到你的项目中,特别是在微服务架构中。下面将详细阐述相关知识点。 1. **Redis简介**:Redis是一个开源(BSD许可)的,基于网络的,...