`

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

<?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: 

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;
				}
			}
		});
    }
}

 

  • 大小: 36.6 KB
  • 大小: 53.7 KB
分享到:
评论

相关推荐

    MATLAB实现基于LSTM-AdaBoost长短期记忆网络结合AdaBoost时间序列预测(含模型描述及示例代码)

    内容概要:本文档详细介绍了基于 MATLAB 实现的 LSTM-AdaBoost 时间序列预测模型,涵盖项目背景、目标、挑战、特点、应用领域以及模型架构和代码示例。随着大数据和AI的发展,时间序列预测变得至关重要。传统方法如 ARIMA 在复杂非线性序列中表现欠佳,因此引入了 LSTM 来捕捉长期依赖性。但 LSTM 存在易陷局部最优、对噪声鲁棒性差的问题,故加入 AdaBoost 提高模型准确性和鲁棒性。两者结合能更好应对非线性和长期依赖的数据,提供更稳定的预测。项目还展示了如何在 MATLAB 中具体实现模型的各个环节。 适用人群:对时间序列预测感兴趣的开发者、研究人员及学生,特别是有一定 MATLAB 编程经验和熟悉深度学习或机器学习基础知识的人群。 使用场景及目标:①适用于金融市场价格预测、气象预报、工业生产故障检测等多种需要时间序列分析的场合;②帮助使用者理解并掌握将LSTM与AdaBoost结合的实现细节及其在提高预测精度和抗噪方面的优势。 其他说明:尽管该模型有诸多优点,但仍存在训练时间长、计算成本高等挑战。文中提及通过优化数据预处理、调整超参数等方式改进性能。同时给出了完整的MATLAB代码实现,便于学习与复现。

    palkert_3ck_01_0918.pdf

    palkert_3ck_01_0918

    pepeljugoski_01_1106.pdf

    pepeljugoski_01_1106

    tatah_01_1107.pdf

    tatah_01_1107

    [AB PLC例程源码][MMS_046393]Motor Speed Reference.zip

    AB PLC例程代码项目案例 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我!

    基于51的步进电机控制系统20250302

    题目:基于单片机的步进电机控制系统 模块: 主控:AT89C52RC 步进电机(ULN2003驱动) 按键(3个) 蓝牙(虚拟终端模拟) 功能: 1、可以通过蓝牙远程控制步进电机转动 2、可以通过按键实现手动与自动控制模式切换。 3、自动模式下,步进电机正转一圈,反转一圈,循环 4、手动模式下可以通过按键控制步进电机转动(顺时针和逆时针)

    [AB PLC例程源码][MMS_041234]Logix Fault Handler.zip

    AB PLC例程代码项目案例 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我!

    [AB PLC例程源码][MMS_042348]Using an Ultra3000 as an Indexer on DeviceNet with a CompactLogix.zip

    AB PLC例程代码项目案例 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我!

    智慧校园平台建设全流程详解:从需求到持续优化

    内容概要:本文详细介绍了建设智慧校园平台所需的六个关键步骤。首先通过需求分析深入了解并确定校方和使用者的具体需求;其次是规划设计阶段,依据所得需求制定全面的建设方案。再者是对现有系统的整合——系统集成,确保新旧平台之间的互操作性和数据一致性。培训支持帮助全校教职工和学生快速熟悉新平台,提高效率。实施试点确保系统逐步稳定部署。最后,强调持续改进的重要性,以适应技术和环境变化。通过这一系列有序的工作,可以使智慧校园建设更为科学高效,减少失败风险。 适用人群:教育领域的决策者和技术人员,包括负责信息化建设和运维的团队成员。 使用场景及目标:用于指导高校和其他各级各类学校规划和发展自身的数字校园生态链;目的是建立更加便捷高效的现代化管理模式和服务机制。 其他说明:智慧校园不仅仅是简单的IT设施升级或软件安装,它涉及到全校范围内的流程再造和创新改革。

    AI淘金实战手册:100+高收益变现案例解析

    该文档系统梳理了人工智能技术在商业场景中的落地路径,聚焦内容生产、电商运营、智能客服、数据分析等12个高潜力领域,提炼出100个可操作性变现模型。内容涵盖AI工具开发、API服务收费、垂直场景解决方案、数据增值服务等多元商业模式,每个思路均配备应用场景拆解、技术实现路径及收益测算框架。重点呈现低代码工具应用、现有平台流量复用、细分领域自动化改造三类轻量化启动方案,为创业者提供从技术选型到盈利闭环的全流程参考。

    palkert_3ck_02_0719.pdf

    palkert_3ck_02_0719

    2006-2023年 地级市-克鲁格曼专业化指数.zip

    克鲁格曼专业化指数,最初是由Krugman于1991年提出,用于反映地区间产业结构的差异,也被用来衡量两个地区间的专业化水平,因而又称地区间专业化指数。该指数的计算公式及其含义可以因应用背景和具体需求的不同而有所调整,但核心都是衡量地区间的产业结构差异或专业化程度。 指标 年份、城市、第一产业人数(first_industry1)、第二产业人数(second_industry1)、第三产业人数(third_industry1)、专业化指数(ksi)。

    [AB PLC例程源码][MMS_046305]R2FX.zip

    AB PLC例程代码项目案例 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我!

    精品推荐-通信技术LTE干货资料合集(19份).zip

    精品推荐,通信技术LTE干货资料合集,19份。 LTE PCI网络规划工具.xlsx LTE-S1切换占比专题优化分析报告.docx LTE_TDD问题定位指导书-吞吐量篇.docx LTE三大常见指标优化指导书.xlsx LTE互操作邻区配置核查原则.docx LTE信令流程详解指导书.docx LTE切换问题定位指导一(定位思路和问题现象).docx LTE劣化小区优化指导手册.docx LTE容量优化高负荷小区优化指导书.docx LTE小区搜索过程学习.docx LTE小区级与邻区级切换参数说明.docx LTE差小区处理思路和步骤.docx LTE干扰日常分析介绍.docx LTE异频同频切换.docx LTE弱覆盖问题分析与优化.docx LTE网优电话面试问题-应答技巧.docx LTE网络切换优化.docx LTE高负荷小区容量优化指导书.docx LTE高铁优化之多频组网优化提升“用户感知,网络价值”.docx

    matlab程序代码项目案例:matlab程序代码项目案例matlab中Toolbox中带有的模型预测工具箱.zip

    matlab程序代码项目案例 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我!

    pepeljugoski_01_0508.pdf

    pepeljugoski_01_0508

    szczepanek_01_0308.pdf

    szczepanek_01_0308

    oif2007.384.01_IEEE.pdf

    oif2007.384.01_IEEE

    stone_3ck_01_0119.pdf

    stone_3ck_01_0119

    oganessyan_01_1107.pdf

    oganessyan_01_1107

Global site tag (gtag.js) - Google Analytics