org.springframework.data.redis.serializer.RedisSerializer Java Examples

The following examples show how to use org.springframework.data.redis.serializer.RedisSerializer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: demo-project   Author: FleyX   File: RedisConfig.java    License: MIT License 6 votes vote down vote up
@Bean(name = "redisTemplate")
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);

    // 设置RedisTemplate
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    RedisSerializer stringSerializer = new StringRedisSerializer();
    template.setKeySerializer(stringSerializer);
    template.setValueSerializer(serializer);
    template.setHashKeySerializer(stringSerializer);
    template.setHashValueSerializer(serializer);
    template.afterPropertiesSet();
    return template;
}
 
Example #2
Source Project: mica   Author: lets-mica   File: RedisTemplateConfiguration.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * value 值 序列化
 *
 * @return RedisSerializer
 */
@Bean
@ConditionalOnMissingBean(RedisSerializer.class)
public RedisSerializer<Object> redisSerializer(MicaRedisProperties properties,
											   ObjectProvider<ObjectMapper> objectProvider) {
	MicaRedisProperties.SerializerType serializerType = properties.getSerializerType();
	if (MicaRedisProperties.SerializerType.JDK == serializerType) {
		return new JdkSerializationRedisSerializer();
	}
	// jackson findAndRegisterModules,use copy
	ObjectMapper objectMapper = objectProvider.getIfAvailable(ObjectMapper::new).copy();
	// findAndRegisterModules
	objectMapper.findAndRegisterModules();
	// class type info to json
	GenericJackson2JsonRedisSerializer.registerNullValueSerializer(objectMapper, null);
	objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), DefaultTyping.NON_FINAL, As.PROPERTY);
	return new GenericJackson2JsonRedisSerializer(objectMapper);
}
 
Example #3
Source Project: springboot_cwenao   Author: cwenao   File: RedisConfig.java    License: MIT License 6 votes vote down vote up
@Bean(name="redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

    RedisTemplate<String, String> template = new RedisTemplate<>();


    RedisSerializer<String> redisSerializer = new StringRedisSerializer();

    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    template.setConnectionFactory(factory);
    //key序列化方式
    template.setKeySerializer(redisSerializer);
    //value序列化
    template.setValueSerializer(jackson2JsonRedisSerializer);
    //value hashmap序列化
    template.setHashValueSerializer(jackson2JsonRedisSerializer);

    return template;
}
 
Example #4
Source Project: open-cloud   Author: liuyadu   File: RedisCacheAutoConfiguration.java    License: MIT License 6 votes vote down vote up
/**
 * 重新配置一个RedisTemplate
 *
 * @param factory
 * @return
 */
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
    template.setConnectionFactory(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    // key采用String的序列化方式
    template.setKeySerializer(stringSerializer);
    // hash的key也采用String的序列化方式
    template.setHashKeySerializer(stringSerializer);
    // value序列化方式采用jackson
    template.setValueSerializer(jackson2JsonRedisSerializer);
    // hash的value序列化方式采用jackson
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.setDefaultSerializer(jackson2JsonRedisSerializer);
    return template;
}
 
Example #5
/**
 * 批量新增 使用pipeline方式
 */
@Override
public boolean add(final List<UserDTO> list) {
	Assert.notEmpty(list);
	boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
		@Override
		public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
			RedisSerializer<String> serializer = getRedisSerializer();
			for (UserDTO userDTO : list) {
				byte[] key = serializer.serialize(userDTO.getId());
				byte[] name = serializer.serialize(userDTO.getName());
				connection.setNX(key, name);
			}
			return true;
		}
	}, false, true);
	return result;
}
 
Example #6
Source Project: ext-opensource-netty   Author: xjc-opensource   File: RedisConfig.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean(name="redisTemplateHash")  
@Scope("prototype")
   public RedisTemplate redisTemplateHash(){  
	RedisSerializer valueSerializer = new GsonRedisSerializer(Object.class);
	RedisSerializer keySerializer = new StringRedisSerializer();

       RedisTemplate redisTemplate = new RedisTemplate();    
        
       redisTemplate.setConnectionFactory(jedisConnectionFactory());
       redisTemplate.setKeySerializer(new StringRedisSerializer());  
       redisTemplate.setValueSerializer(new StringRedisSerializer());  
       redisTemplate.setHashKeySerializer(keySerializer);  
       redisTemplate.setHashValueSerializer(valueSerializer);  
       redisTemplate.afterPropertiesSet();  
       redisTemplate.setEnableTransactionSupport(true);  
         
       return redisTemplate;    
   }
 
Example #7
Source Project: syhthems-platform   Author: ehaut   File: RedisCacheConfig.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Bean
public CacheManager JDKCacheManager() {
    final RedisCacheWriter redisCacheWriter =
            RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
    final RedisCacheConfiguration defaultCacheConfig =
            RedisCacheConfiguration.defaultCacheConfig()

                    // 不缓存 null 值
                    .disableCachingNullValues()
                    // 使用注解时的序列化、反序列化对
                    .serializeKeysWith(stringPair)
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.java()))
                    .prefixKeysWith("syhthems:cache:");
    return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
 
Example #8
Source Project: blog_demos   Author: zq2599   File: RedisClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 更新缓存中的对象,也可以在redis缓存中存入新的对象
 *
 * @param key
 * @param t
 * @param <T>
 */
public <T> void set(String key, T t) {
    byte[] keyBytes = getKey(key);
    RedisSerializer serializer = redisTemplate.getValueSerializer();
    byte[] val = serializer.serialize(t);
    RedisConnection redisConnection = getConnection();

    if(null!=redisConnection){
        try {
            redisConnection.set(keyBytes, val);
        }finally {
            releaseConnection(redisConnection);
        }
    }else{
        logger.error("1. can not get valid connection");
    }
}
 
Example #9
Source Project: springboot_cwenao   Author: cwenao   File: RedisConfig.java    License: MIT License 6 votes vote down vote up
@Bean(name="redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

    RedisTemplate<String, String> template = new RedisTemplate<>();


    RedisSerializer<String> redisSerializer = new StringRedisSerializer();

    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    template.setConnectionFactory(factory);
    //key序列化方式
    template.setKeySerializer(redisSerializer);
    //value序列化
    template.setValueSerializer(jackson2JsonRedisSerializer);
    //value hashmap序列化
    template.setHashValueSerializer(jackson2JsonRedisSerializer);

    return template;
}
 
Example #10
Source Project: soul   Author: Dromara   File: RateLimiterPluginDataHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handlerPlugin(final PluginData pluginData) {
    if (Objects.nonNull(pluginData) && pluginData.getEnabled()) {
        //init redis
        RateLimiterConfig rateLimiterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), RateLimiterConfig.class);
        //spring data redisTemplate
        if (Objects.isNull(Singleton.INST.get(ReactiveRedisTemplate.class))
                || Objects.isNull(Singleton.INST.get(RateLimiterConfig.class))
                || !rateLimiterConfig.equals(Singleton.INST.get(RateLimiterConfig.class))) {
            LettuceConnectionFactory lettuceConnectionFactory = createLettuceConnectionFactory(rateLimiterConfig);
            lettuceConnectionFactory.afterPropertiesSet();
            RedisSerializer<String> serializer = new StringRedisSerializer();
            RedisSerializationContext<String, String> serializationContext =
                    RedisSerializationContext.<String, String>newSerializationContext().key(serializer).value(serializer).hashKey(serializer).hashValue(serializer).build();
            ReactiveRedisTemplate<String, String> reactiveRedisTemplate = new ReactiveRedisTemplate<>(lettuceConnectionFactory, serializationContext);
            Singleton.INST.single(ReactiveRedisTemplate.class, reactiveRedisTemplate);
            Singleton.INST.single(RateLimiterConfig.class, rateLimiterConfig);
        }
    }
}
 
Example #11
Source Project: SpringBoot2.0   Author: drinkagain   File: RedisRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据key获取对象
 *
 * @param keyPatten the key patten
 * @return the keys values
 */
public Map<String, Object> getKeysValues(final String keyPatten) {
    log.debug("[redisTemplate redis]  getValues()  patten={} ", keyPatten);
    return redisTemplate.execute((RedisCallback<Map<String, Object>>) connection -> {
        RedisSerializer<String> serializer = getRedisSerializer();
        Map<String, Object> maps = new HashMap<>(16);
        Set<String> keys = redisTemplate.keys(keyPatten + "*");
        if (!CollectionUtils.isEmpty(keys)) {
            for (String key : keys) {
                byte[] bKeys = serializer.serialize(key);
                byte[] bValues = connection.get(bKeys);
                Object value = OBJECT_SERIALIZER.deserialize(bValues);
                maps.put(key, value);
            }
        }
        return maps;
    });
}
 
Example #12
Source Project: onetwo   Author: wayshall   File: JsonValueRedisTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/***
	 * 构造后需要调用setConnectionFactory, afterPropertiesSet
	 * @param valueType
	 */
	public JsonValueRedisTemplate(Class<T> valueType) {
//		this.valueType = (Class<T>)ReflectUtils.getGenricType(getClass(), 0);
		this.valueType = valueType;
		RedisSerializer<String> keySerializer = new StringRedisSerializer();
		RedisSerializer<?> valueSerializer = null;
		if (valueType==null || valueType==Object.class) {
			valueSerializer = RedisUtils.typingJackson2RedisSerializer();
		} else {
			valueSerializer = new Jackson2JsonRedisSerializer<T>(valueType);
		}
		setKeySerializer(keySerializer);
		setValueSerializer(valueSerializer);
		setHashKeySerializer(keySerializer);
		setHashValueSerializer(valueSerializer);
	}
 
Example #13
Source Project: blog_demos   Author: zq2599   File: RedisClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 更新缓存中的对象,也可以在redis缓存中存入新的对象
 *
 * @param key
 * @param t
 * @param <T>
 */
public <T> void set(String key, T t) {
    byte[] keyBytes = getKey(key);
    RedisSerializer serializer = redisTemplate.getValueSerializer();
    byte[] val = serializer.serialize(t);
    RedisConnection redisConnection = getConnection();

    if(null!=redisConnection){
        try {
            redisConnection.set(keyBytes, val);
        }finally {
            releaseConnection(redisConnection);
        }
    }else{
        logger.error("1. can not get valid connection");
    }
}
 
Example #14
Source Project: Taroco   Author: liuht777   File: TarocoRedisRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据key获取对象
 *
 * @param keyPatten the key patten
 * @return the keys values
 */
public Map<String, String> getKeysValues(final String keyPatten) {
    log.debug("[redisTemplate redis]  getValues()  patten={} ", keyPatten);
    return redisTemplate.execute((RedisCallback<Map<String, String>>) connection -> {
        RedisSerializer<String> serializer = getRedisSerializer();
        Map<String, String> maps = new HashMap<>(16);
        Set<String> keys = redisTemplate.keys(keyPatten + "*");
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                byte[] bKeys = serializer.serialize(key);
                byte[] bValues = connection.get(bKeys);
                String value = serializer.deserialize(bValues);
                maps.put(key, value);
            }
        }
        return maps;
    });
}
 
Example #15
Source Project: spring-boot-email-tools   Author: ozimov   File: EmailRedisTemplateConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@Qualifier("valueTemplate")
public RedisTemplate<String, EmailSchedulingData> createValueTemplate() throws IOException {
    RedisTemplate<String, EmailSchedulingData> template = new RedisTemplate<>();
    RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
    template.setKeySerializer(stringSerializer);
    template.setValueSerializer(jdkSerializationRedisSerializer);
    template.setHashKeySerializer(stringSerializer);
    template.setHashValueSerializer(stringSerializer);

    template.setConnectionFactory(redisConnectionFactory);
    template.setEnableTransactionSupport(true);
    template.afterPropertiesSet();
    return template;
}
 
Example #16
/**
 * 通过key获取
 */
@Override
public UserDTO get(final String keyId) {
	UserDTO result = redisTemplate.execute(new RedisCallback<UserDTO>() {
		@Override
		public UserDTO doInRedis(RedisConnection connection) throws DataAccessException {
			RedisSerializer<String> serializer = getRedisSerializer();
			byte[] key = serializer.serialize(keyId);
			byte[] value = connection.get(key);
			if (value == null) {
				return null;
			}
			String name = serializer.deserialize(value);
			return new UserDTO(keyId, name, null);
		}
	});
	return result;
}
 
Example #17
Source Project: spring-music   Author: scottfrederick   File: RedisConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public RedisTemplate<String, Album> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Album> template = new RedisTemplate<>();

    template.setConnectionFactory(redisConnectionFactory);

    RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    RedisSerializer<Album> albumSerializer = new Jackson2JsonRedisSerializer<>(Album.class);

    template.setKeySerializer(stringSerializer);
    template.setValueSerializer(albumSerializer);
    template.setHashKeySerializer(stringSerializer);
    template.setHashValueSerializer(albumSerializer);

    return template;
}
 
Example #18
Source Project: common-project   Author: yz-java   File: DistributedLock.java    License: Apache License 2.0 6 votes vote down vote up
public boolean lock(String key, long time, TimeUnit timeUnit){
    List<Boolean> results = redisTemplate.executePipelined(new RedisCallback<Boolean>() {

        RedisSerializer keySerializer = redisTemplate.getKeySerializer();

        RedisSerializer valueSerializer = redisTemplate.getValueSerializer();

        @Override
        public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
            redisConnection.openPipeline();
            byte[] keySerialize = keySerializer.serialize(key);
            byte[] valueSerialize = valueSerializer.serialize(System.currentTimeMillis());
            redisConnection.setNX(keySerialize, valueSerialize);
            long l = timeUnit.toSeconds(time);
            redisConnection.expire(keySerialize, l);
            return null;
        }
    });
    for (Boolean result :results) {
        if (!result){
            return false;
        }
    }
    return true;
}
 
Example #19
Source Project: mica   Author: lets-mica   File: MicaRedisCacheAutoConfiguration.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
MicaRedisCacheAutoConfiguration(RedisSerializer<Object> redisSerializer,
								CacheProperties cacheProperties,
								CacheManagerCustomizers customizerInvoker,
								ObjectProvider<RedisCacheConfiguration> redisCacheConfiguration) {
	this.redisSerializer = redisSerializer;
	this.cacheProperties = cacheProperties;
	this.customizerInvoker = customizerInvoker;
	this.redisCacheConfiguration = redisCacheConfiguration.getIfAvailable();
}
 
Example #20
Source Project: MyCommunity   Author: UHungLin   File: RedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
    // RedisConnectionFactory 连接工厂,Spring会自动注入这个Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 设置key的序列化方式
        template.setKeySerializer(redisSerializer); // 序列化为String
        // 设置value的序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
//        // 设置hash的key的序列化方式   当value为hash时,hash有key和value,所以需要设置
//        template.setHashKeySerializer(RedisSerializer.string());
//        // 设置hash的value的序列化方式
//        template.setHashValueSerializer(RedisSerializer.json());
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();  // 使上面设置生效
        return template;
    }
 
Example #21
Source Project: onetwo   Author: wayshall   File: RedisUtils.java    License: Apache License 2.0 5 votes vote down vote up
static public RedisSerializer<Object> typingJackson2RedisSerializer() {
		JsonMapper jsonMapper = JsonMapper.ignoreNull();
		ObjectMapper mapper = jsonMapper.getObjectMapper();
		mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);//用这个配置,如果写入的对象是list,并且元素是复合对象时,会抛错:Current context not Object but Array
//		mapper.enableDefaultTyping(DefaultTyping.JAVA_LANG_OBJECT);
		RedisSerializer<Object> valueSerializer = new GenericJackson2JsonRedisSerializer(mapper);
		return valueSerializer;
	}
 
Example #22
Source Project: Demo   Author: turoDog   File: RedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@SuppressWarnings("unchecked")
public RedisTemplate<String, Object> redisTemplate() {
    RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    //RedisSerializer<Object> jsonString = new GenericToStringSerializer<>(Object.class);
    RedisSerializer<Object> jsonString = new FastJsonRedisSerializer<>(Object.class);
    // String 的 key 和 hash 的 key 都采用 String 的序列化方式
    redisTemplate.setKeySerializer(stringSerializer);
    redisTemplate.setHashKeySerializer(stringSerializer);
    // value 都采用 fastjson 的序列化方式
    redisTemplate.setValueSerializer(jsonString);
    redisTemplate.setHashValueSerializer(jsonString);
    return redisTemplate;
}
 
Example #23
Source Project: spring-security   Author: hello-shf   File: RedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "myRedisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(stringSerializer);
    template.setKeySerializer(stringSerializer);
    template.afterPropertiesSet();
    return template;
}
 
Example #24
Source Project: mall-learning   Author: macrozheng   File: RedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RedisSerializer<Object> redisSerializer() {
    //创建JSON序列化器
    Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(objectMapper);
    return serializer;
}
 
Example #25
Source Project: White-Jotter   Author: Antabot   File: RedisConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public RedisSerializer<Object> redisSerializer() {
    //创建JSON序列化器
    Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(objectMapper);
    return serializer;
}
 
Example #26
Source Project: kvf-admin   Author: kalvinGit   File: RedisConfig.java    License: MIT License 5 votes vote down vote up
/**
 * RedisTemplate配置
 * @param factory redis链接工厂
 * @return RedisTemplate
 */
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    RedisSerializer<String> redisSerializer = new StringRedisSerializer();

    // 设置序列化,key采用redisSerializer,value采用jackson2JsonRedisSerializer
    template.setConnectionFactory(factory);
    template.setKeySerializer(redisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer());
    template.setHashKeySerializer(redisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer());
    template.afterPropertiesSet();
    return template;
}
 
Example #27
Source Project: ext-opensource-netty   Author: xjc-opensource   File: RedisHashServiceImpl.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Resource(name="redisTemplateHash")
private void setRedisTemplate(RedisTemplate<String, V> redisTemplateHash) {
	this.redisTemplate = redisTemplateHash;
	hkeySerializer = (RedisSerializer<String>) redisTemplate.getStringSerializer();
	hvalueSerializer = (RedisSerializer<V>) redisTemplate.getHashValueSerializer();
	serializer = redisTemplate.getStringSerializer();
	//System.err.println(hkeySerializer.getClass().getSimpleName());
}
 
Example #28
Source Project: redis-admin   Author: mauersu   File: MyStringRedisTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}
 * and {@link #afterPropertiesSet()} still need to be called.
 */
public MyStringRedisTemplate() {
	RedisSerializer<String> stringSerializer = new StringRedisSerializer();
	setKeySerializer(stringSerializer);
	setValueSerializer(stringSerializer);
	setHashKeySerializer(stringSerializer);
	setHashValueSerializer(stringSerializer);
}
 
Example #29
Source Project: ext-opensource-netty   Author: xjc-opensource   File: RedisServiceImpl.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Long incr(final String key) {
    Long result = redisTemplate.execute(new RedisCallback<Long>() {

        @Override
        public Long doInRedis(RedisConnection connection) throws DataAccessException {
            RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
            return connection.incr(serializer.serialize(key));
        }
    });
    return result;
}
 
Example #30
Source Project: ext-opensource-netty   Author: xjc-opensource   File: RedisServiceImpl.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public long lpush(final String key, Object obj) {
    final String value = JosnRedisUtil.toJson(obj);
    long result = redisTemplate.execute(new RedisCallback<Long>() {

        @Override
        public Long doInRedis(RedisConnection connection) throws DataAccessException {
            RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
            long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
            return count;
        }
    });
    return result;
}