springboot整合redis使用介绍

springboot整合redis使用介绍,第1张

前言

本文介绍了springboot集成redis需要的一些配置以及常见的redis *** 作工具类。


提示:以下是本篇文章正文内容,下面案例可供参考

一、redis是什么?

redis是一个高性能、基于内存级别读写的非关系型数据库

二、使用步骤 引入库
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
dependency>
<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-pool2artifactId>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
dependency>
定义配置类 数据序列化以及反序列化
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class<T> clazz;

    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        //禁用关键字检测
        return JSON.parseObject(str, clazz, Feature.DisableSpecialKeyDetect);
    }
}
属性配置
@Data
@ConfigurationProperties(
        prefix = "spring.myredis"
)
@Component(value = "MyRedisProperties")
public class MyRedisProperties{
    /**备用数据库 */
    private Integer backupdb;
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String username;
    private String password;
    private int port = 6379;
    private boolean ssl;
    private Duration timeout;
    private Duration connectTimeout;
}
主从库配置
@Configuration
@EnableConfigurationProperties
@EnableCaching
public class RedisConfig {
    @Resource
    MyRedisProperties myRedisProperties;

    /**
     * 默认的redis模板类,使用默认数据库访问
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    @Primary
    public RedisTemplate redisTemplateMaster(RedisConnectionFactory redisConnectionFactory){
        // 创建redis序列化器
        RedisTemplate redisTemplate = new RedisTemplate<>();
        FastJsonRedisSerializer<Object> objectFastJson2JsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        redisTemplate.setKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 备用数据库
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplateSlave(RedisConnectionFactory connectionFactory){
        // 创建redis序列化器
        RedisTemplate redisTemplate = new RedisTemplate<>();
        FastJsonRedisSerializer<Object> objectFastJson2JsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        redisTemplate.setKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(objectFastJson2JsonRedisSerializer);
        if(connectionFactory instanceof  LettuceConnectionFactory){
            //创建客户端连接
            LettuceConnectionFactory lettuceConnectionFactory =
                    createLettuceConnectionFactory
                            (myRedisProperties.getBackupdb(),myRedisProperties.getHost(),myRedisProperties.getPort(),myRedisProperties.getPassword(),myRedisProperties.getTimeout().getSeconds()*1000);
            redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        }
        return redisTemplate;
    }

    /**
     * 创建lettuce连接工厂
     * @param dbIndex
     * @param hostName
     * @param port
     * @param password
     * @param timeOut
     * @return
     */
    private  LettuceConnectionFactory createLettuceConnectionFactory(
            int dbIndex, String hostName, int port, String password,
            Long timeOut){
        //redis配置
        RedisConfiguration redisConfiguration = new
                RedisStandaloneConfiguration(hostName,port);
        ((RedisStandaloneConfiguration) redisConfiguration).setDatabase(dbIndex);
        ((RedisStandaloneConfiguration) redisConfiguration).setPassword(password);
        //连接池配置
        GenericObjectPoolConfig genericObjectPoolConfig =
                new GenericObjectPoolConfig();
        //redis客户端配置
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
                builder =  LettucePoolingClientConfiguration.builder().
                commandTimeout(Duration.ofMillis(timeOut));
        builder.poolConfig(genericObjectPoolConfig);
        LettuceClientConfiguration lettuceClientConfiguration = builder.build();
        //根据配置和客户端配置创建连接
        LettuceConnectionFactory lettuceConnectionFactory = new
                LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration);
        lettuceConnectionFactory .afterPropertiesSet();
        return lettuceConnectionFactory;
    }

}
常用 *** 作工具类
public class RedisUtils {
    public RedisTemplate redisTemplate;

    public RedisUtils(Boolean isMaster) {
        if (isMaster) {
            redisTemplate = SpringUtil.getBean("redisTemplateMaster");
            return;
        }
        redisTemplate = SpringUtil.getBean("redisTemplateSlave");
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public void setObject(final String key, final Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public  void setObject(final String key, final Object value, final Long timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public Object getObject(final String key) {
        return redisTemplate.opsForValue().get(key);
    }
    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getObject(final String key,final Class<T> clazz) {
        return JSONUtil.toBean(JSONUtil.toJsonStr(redisTemplate.opsForValue().get(key)),clazz);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public long setList(final String key, final Collection dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public List getList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getList(final String key,final Class<T> clazz) {
        return JSONUtil.toList(JSONUtil.toJsonStr(redisTemplate.opsForList().range(key, 0, -1)),clazz);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public void setSet(final String key, final Set dataSet) {
        redisTemplate.opsForSet().add(key, dataSet);
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public Set getSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public void setMap(final String key, final Map<String, Object> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public Map getMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public void setMap(final String key, final String hKey, final Object value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public Object getMap(final String key, final String hKey) {
        return redisTemplate.opsForHash().get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public List getMap(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }
}

启动配置application.yml
spring:
  myredis:
    database: 0
    backupdb: 1
    host: localhost
    port: 6379
    timeout: 30
运行启动类
@SpringBootTest(classes = SpringBootExampleApplication.class)
@Slf4j
@RunWith(SpringRunner.class)
public class RedisTest {
    /**
     * redis 数据库切换测试
     * 包括主数据库master以及备用数据库slave
     */
    @Test
    public void testRedis(){
        String STRING_KEY = "testString";
        String LIST_KEY = "testList";
        String HASH_KEY = "testHash";
        String SET_KEY = "testSet";
        RedisUtils redisUtils = new RedisUtils(true);
        RedisUtils redisUtilSalve = new RedisUtils(false);

        // string *** 作
        redisUtils.setObject(STRING_KEY,"test");
        redisUtilSalve.setObject(STRING_KEY,new Student(20,"小明"));
        // list *** 作
        redisUtils.setList(LIST_KEY, Arrays.asList(1,2));
        redisUtilSalve.setList(LIST_KEY,Arrays.asList(new Student(1,"1"),new Student(2,"2")));
        // map *** 作
        redisUtils.setMap(HASH_KEY, MapUtil.of(HASH_KEY,"test"));
        redisUtilSalve.setMap(HASH_KEY,MapUtil.of(HASH_KEY,"testSlave"));
        // set  *** 作
        HashSet hashSet = new HashSet();
        hashSet.add("test");
        hashSet.add("test1");
        redisUtils.setSet(SET_KEY,hashSet);
        hashSet.add("testSalve");
        redisUtilSalve.setSet(SET_KEY,hashSet);

        // 打印展示
        // string打印
        System.out.println(redisUtils.getObject(STRING_KEY));
        Student student = redisUtilSalve.getObject(STRING_KEY, Student.class);
        System.out.println(student);
        // list 打印
        System.out.println(redisUtils.getList(LIST_KEY));
        List<Student> studentList = redisUtilSalve.getList(LIST_KEY,Student.class);
        studentList.stream().forEach(System.out::println);
        // map 打印
        redisUtils.getMap(HASH_KEY).forEach((k,v)->{
            System.out.println(k+":"+v);
        });
        redisUtilSalve.getMap(HASH_KEY).forEach((k,v)->{
            System.out.println(k+":"+v);
        });
        // set 打印
        redisUtils.getSet(SET_KEY).forEach(v->{
            System.out.println(v);
        });
        redisUtilSalve.getSet(SET_KEY).forEach(v->{
            System.out.println(v);
        });
    }
}
打印效果
=======string打印======
test
Student(age=20, name=小明)
=======list打印======
[1, 2]
Student(age=1, name=1)
Student(age=2, name=2)
=======map打印======
testHash:test
testHash:testSlave
=======set打印======
[test, test1]
[test, testSalve, test1]
Another Redis Desktop Manager 工具效果


总结

以上就是介绍的全部内容,把一些常用便捷的方法封装进去,方便后续二次开发引用。

源码地址

测试代码地址在:https://gitee.com/teajoy/springboot-modules/tree/master/springboot-example

https://gitee.com/teajoy/springboot-modules/tree/master/springboot-redis

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/905046.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存