spring-data-redis实战

阅读更多

    

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集成文件如下:




	
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
	
		
		
		
		
		
	

 

    2)sentinel部署模式

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




	
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
		
			
				
			
		
		
			
				
					
					
				
				
					
					
				
				
					
					
				
			
		
	
	
		
	
	
		
		
		
		
		
	

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

 

    3)redis-cluster部署模式

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




	
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
		
		
			
				
					
					
				
				
					
					
				
				
					
					
				
				
					
					
				
				
					
					
				
				
					
					
				
			
		
	
	
		
	
	
		
		
		
		
		
	

 

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实战_第1张图片
     这里我使用的是最新的1.7.5.RELEASE版本,点击上图pom链接进去搜索jedis,即可查看到jedis版本,如下:
spring-data-redis实战_第2张图片
     所以最后我的maven依赖如下:

		
			redis.clients
			jedis
			2.8.1
		
		
			org.springframework.data
			spring-data-redis
			1.7.5.RELEASE
		

 

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.(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.(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.(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.(Ljava/lang/ClassLoader;)V
at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.(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.(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 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() {
			@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() {
			@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() {
			@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() {
			@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 smembers(final String key) {
    	return (Set) redisTemplate.execute(new RedisCallback() {
			@Override
			public Set doInRedis(RedisConnection connection) throws DataAccessException {
				Set returnSet = new HashSet();
				byte[] keyBytes = SafeEncoder.encode(key);
				Set 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 hgetAll(final String key) {
		return (Map) redisTemplate.execute(new RedisCallback() {
			@Override
			public Map doInRedis(RedisConnection connection) throws DataAccessException {
				Map returnMap = new HashMap();
				byte[] keyBytes = SafeEncoder.encode(key);
					Map bytesMap = connection.hGetAll(keyBytes);
					if (null != bytesMap && bytesMap.size() > 0) {
						for (Map.Entry entry : bytesMap.entrySet()) {
							returnMap.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue()));
						}
					}
				return returnMap;
			}
		});
    } 

	public Boolean hmset(final String key, final Map hash) {
		return (Boolean) redisTemplate.execute(new RedisCallback() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				try {
				    final Map bhash = new HashMap(hash.size());
				    for (final Entry 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 hash)", e);
					return false;
				}
			}
		});
	}

	public Long srem(final String key, final String... members) {
		return (Long) redisTemplate.execute(new RedisCallback() {
			@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() {
			@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() {
			@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() {
			@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实战_第3张图片
  • 大小: 36.6 KB
  • spring-data-redis实战_第4张图片
  • 大小: 53.7 KB
  • 查看图片附件

你可能感兴趣的:(spring-data-redis实战)