栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合Redis和自定义RedisTemplate、RedisUtil和中文乱码解决

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合Redis和自定义RedisTemplate、RedisUtil和中文乱码解决

SpringBoot操作数据库:Spring Data jpa jdbc mongodb redis
Spring Data也是和SpringBoot齐名的项目!
说明:在SpringBoot2.x之后,原来使用的jedis被替换成了
lettuce(莴苣)
从我们导入的pom文件中去看:



        
            org.springframework.boot
            spring-boot-starter-data-redis
        

可以看到,底层还是spring data的redis,下面的是lettuce包

 
      org.springframework.data
      spring-data-redis
      2.7.1
      compile
    
    
      io.lettuce
      lettuce-core
      6.1.8.RELEASE
      compile
    

为什么要替换呢?
jedis:采用的是直连的方式,多个线程操作的话,是不安全的,要解决不安全的问题,需要采用jedis pool线程池。BIO模式
lettuce:采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!性能也更高,可以减少线程数量,更像NIO模式
BIO和NIO的区别

源码分析:
在springboot的自动配置文件中可以看到:

点进这个自动配置类可以看到:

再点进这个redis默认配置类,可以看到redis的默认配置,如果你是本机安装并使用redis,都不用在application.properties里配置

再回去看这个RedisAutoConfigration类:

springboot整合redis

1、导入依赖


        
            org.springframework.boot
            spring-boot-starter-data-redis
        

2、配置连接

# 配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379


3、测试!
== springboot中redis的操作与linux操作redis命令略有区别==

package com.uno;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;

@SpringBootTest
class Redis02SpringbootApplicationTests {

    @Resource  //用不了@Autowired,就用@Resource
    private RedisTemplate redisTemplate;
    
    @Test
    void contextLoads() {
        //操作不同的数据类型,api和我们的指令是一样的
        //ops:Operations的缩写,意思为操作,opsForValue是操作redis中string类型的
        redisTemplate.opsForValue().set("mmm","haxilama");
        System.out.println(redisTemplate.opsForValue().get("mmm"));

        //操作redis中list类型,往里面设置一个list1放两个string
        redisTemplate.opsForList().leftPush("list1","aaa");
        redisTemplate.opsForList().rightPush("list1","bbb");
        System.out.println(redisTemplate.opsForList().range("list1",0,-1));;

        //一些基本的命令,可以使用redisTemplate直接操作,比如事务等
//        redisTemplate.multi();
//        redisTemplate.exec();
//        redisTemplate.discard();
//        redisTemplate.delete("mmm");

        //获取redis连接,进行一些命令
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushDb(); //清空当前数据库,redis有16个数据库
        connection.flushAll(); //清空所有数据库
    }
}
``
执行结果:
```xml
haxilama
[aaa, bbb]

ops:Operations(操作)的简写,后面跟要操作的类型
我们常用的方法都可以直接通过redisTemplate操作,比如事务,和基本的CRUD

自定义RedisTemplate

redis序列化:

当我们给redis设置一些中文的键值对的时候,会出现乱码问题,是序列化的问题,接下来我们尝试自定义RedisTemplate,来解决序列化乱码的问题

RedisTemplate默认使用jdk的序列化

我们先来实验一些,没有序列化,能否和redis进行传输对象


很明显,没有序列化,不能存入redis
序列化一下,看能不能成功:


这里虽然成功了,但是是jdk自带的序列化方式,这样的序列化方式在redis中存的数据是什么样的呢?
直接去redis里看我们存的user对象:user前面一堆乱码(转义字符),说明没有序列化成功

127.0.0.1:6379> keys *
1) "xacxedx00x05tx00x04user"

所以得出:所有的对象都必须合理的序列化,才能和redis传输,并且存储正确、方便的值

接下来我们自己定义一个RedisTemplate类:

package com.uno.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

//编写我们自己的RedisTemplate
@Configuration
public class RedisConfig {
    //固定redis模板,在工作中,拿去就可以用
    @Bean
    @SuppressWarnings("all")
    //改成String,Object类型
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        //我们为了自己开发方便,一般直接使用
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(factory);

        //Json序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //String 的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //key采用string的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //value的序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}

由于我们自己写的RedisTemplate生效了,默认的由于
@ConditionalOnMissingBean(name = {“redisTemplate”})
就失效了,注意在使用RedisTemplate的时候,要用自己的

再次测试,结果:

去redis里看看,是否序列化成功:

127.0.0.1:6379> keys *
1) "user"

redis存的不是乱码了,是对象名了,说明对象序列化成功

RedisUtil类

在企业开发中,我们80%的情况下,都不会使用这些原生的方式去编写代码!

 		redisTemplate.opsForValue().set("mmm","haxilama");
        System.out.println(redisTemplate.opsForValue().get("mmm"));

        //操作redis中list类型,往里面设置一个list1放两个string
        redisTemplate.opsForList().leftPush("list1","aaa");
        redisTemplate.opsForList().rightPush("list1","bbb");
        System.out.println(redisTemplate.opsForList().range("list1",0,-1));

我们需要一个RedisUtil类或者RedisTools类来帮助我们处理异常等操作,更为便捷

package com.uno.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;
    
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
    
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));
            }
        }
    }
    // ============================String=============================
    
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
    
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
    // ================================Map=================================
    
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    
    public Map hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    
    public boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean hmset(String key, Map map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }
    
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }
    
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }
    
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
    // ============================set=============================
    
    public Set sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================
    
    public List lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lSet(String key, List value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
 

RedisUtil的使用:

    @Autowired
    private RedisUtil redisUtil;  //导入redisUtil

    @Test
    public void test2(){
        redisUtil.set("name", "基尼太美");  //直接使用
        System.out.println(redisUtil.get("name"));
    }

执行结果

基尼太美

以上

注:如果使用java代码设置的中文值,在redis-cli中查看是中文乱码
1、如果是这种乱码:

""bbbbxe5x9fxbaxe5xb0xbcxe5xa4xaaxe7xbex8e""

那么解决办法是,启动redis-cli的时候,后面加“–raw”后缀,就可以了

2、如果乱码是这种中文的:

涴岆珨跺趼睫摩

那么解决办法是:启动redis-cli之前(redis-cli -p 6379 --raw之前),执行一条命令:

chcp 65001

来改变编码格式为’utf-8’,执行完是这样的

Active code page: 65001

然后你执行redis-cli -p 6379 --raw,就可以正常的看到中文了

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号