springboot redis Template使用,数据乱码解决

springboot提供了redis客户端,可以很方便的和springboot进行集成,一般在pom中引入:

<dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>

然后在配置中进行如下配置:

spring.redis.host=
spring.redis.port=6379
spring.redis.database=1
spring.redis.password=123456
spring.redis.jedis.pool.max-active=50
spring.redis.jedis.pool.max-wait=3000
spring.redis.jedis.pool.max-idle=20
spring.redis.jedis.pool.min-idle=2

在程序里面就可以如下使用:

@Service
public class RedisService {
    
    

    @Autowired
    private RedisTemplate redisTemplate;
  public boolean setNX(String key,String value,long timeoutSeconds) {
    
    
        ValueOperations operations = redisTemplate.opsForValue();
        boolean result = operations.setIfAbsent(key,value,timeoutSeconds,TimeUnit.SECONDS);
        return result;
    }

    public void expire(String key,long timeout) {
    
    
        this.redisTemplate.expire(key,timeout,TimeUnit.SECONDS);
    }

    public Object get(Object key) {
    
    
        ValueOperations operations = redisTemplate.opsForValue();
       return  operations.get(key);
    }
    public void set(String key,String value) {
    
    
        this.redisTemplate.opsForValue().set(key,value);
    }

    public void setAndExpire(String key,String value,long timeoutSeconds) {
    
    
        this.redisTemplate.opsForValue().set(key,value,timeoutSeconds,TimeUnit.SECONDS);
    }
    public void remove(String key){
    
    
        this.redisTemplate.delete(key);
    }

    public boolean hasKey(String key) {
    
    
        return this.redisTemplate.hasKey(key);
    }
}

但是如果根据默认的配置,当我们操作redis之后,查看里面的内容,发现是如下乱码,或者说是二进制:
在这里插入图片描述

不是我们正常预期想的那样。
这主要是因为在springboot-redis中,默认配置没有序列化,直接将string转成了byte:

redisTemplate.opsForValue().set(key,value);
public void set(K key, V value) {
    
    

		byte[] rawValue = rawValue(value);
		execute(new ValueDeserializingRedisCallback(key) {
    
    

			@Override
			protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
    
    
				connection.set(rawKey, rawValue);
				return null;
			}
		}, true);
	}
byte[] rawValue(Object value) {
    
    

		if (valueSerializer() == null && value instanceof byte[]) {
    
    
			return (byte[]) value;
		}

		return valueSerializer().serialize(value);
	}

为了解决上述问题,可以增加相关的序列化器:

  @Bean
    public RedisTemplate<String, Object> stringSerializerRedisTemplate() {
    
    
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        return redisTemplate;
    }

这样即可。

Guess you like

Origin blog.csdn.net/LeoHan163/article/details/116707848