SpringBoot-Redis

SpringBoot 整合 Redis

  1. SpringBoot-Redis

15.1 导入相关依赖


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

        org.springframework.boot
        spring-boot-starter-web

        org.springframework.boot
        spring-boot-devtools
        runtime
        true

        org.springframework.boot
        spring-boot-configuration-processor
        true

        org.projectlombok
        lombok
        true

        org.springframework.boot
        spring-boot-starter-test
        test

15.2 编写Redis配置类

文件路径:com–dzj–config–RedisConfig.java

@Configuration
public class RedisConfig {

    //编写我们自己的RedisTemplate
    @Bean
    public RedisTemplate redisTemplates(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();

        //配置具体的序列化方式
        // Json序列化配置
        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);
        // String 的序列化
         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
//        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

15.3 编写测试实体类

文件路径:com–dzj–pojo–User.java

@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User{

    //如果需要序列化,可以实现Serializable接口进行序列化
    private String name;
    private int age;
}

15.4 编写配置文件

SpringBoot所有的配置,都有一个自动配置类 RedisAutoConfiguration
自动配置类都会绑定一个properties配置文件  @EnableConfigurationProperties(RedisProperties.class)

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

15.5 在测试类中进行测试

package com.dzj;

import com.dzj.pojo.User;
import com.dzj.utils.RedisUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class Springboot10RedisApplicationTests {

    @Autowired
    @Qualifier("redisTemplates")
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisUtils redisUtils;

    @Test
    public void testUtils(){
        redisUtils.set("dengzj","hello,redisUtils");
        System.out.println(redisUtils.get("dengzj"));
    }

    @Test
    void contextLoads() {
        /*
            redisTemplate:操作不同的数据类型,api和我们的指令是一样的 redisTemplate.opsForValue();

            opsForValue() 操作字符串,类似String
            opsForList() 操作List,类似List
            opsForSet()、opsForHash()、opsForZSet()、opsForGeo()、opsForHyperLogLog()
            除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务、和基本的CRUD
         */
        /*
            获取redis的连接对象
            RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
            connection.flushDb();
            connection.flushAll();
         */

        redisTemplate.opsForValue().set("mykey","dengzj");
        System.out.println(redisTemplate.opsForValue().get("mykey"));
    }

    @Test
    public void test() throws JsonProcessingException {
        // 真实的开发一般都是用json传递对象
        User user = new User("dengzj", 18);
        //String jsonUser = new ObjectMapper().writeValueAsString(user);  //进行序列化操作
        //redisTemplate.opsForValue().set("user",jsonUser);
        redisTemplate.opsForValue().set("user",user);  //如果没有序列化,直接传递对象会报错
        System.out.println(redisTemplate.opsForValue().get("user"));
    }
}

运行测试!

15.6 Redis工具类

package com.dzj.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 final class RedisUtils{

    @Autowired
    @Qualifier("redisTemplates")
    private RedisTemplate redisTemplate;

    // =============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @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=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 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;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     */
    public boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map map, long time, TimeUnit timeUnit) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 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;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time, TimeUnit timeUnit) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     */
    public Set sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, TimeUnit timeUnit, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time, timeUnit);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */

    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=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
    public List lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index 0) {
                expire(key, time,timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List value, long time,TimeUnit timeUnit) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time,timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

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

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */

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

    }

    // ===============================HyperLogLog=================================

    public long pfadd(String key, String value) {
        return redisTemplate.opsForHyperLogLog().add(key, value);
    }

    public long pfcount(String key) {
        return redisTemplate.opsForHyperLogLog().size(key);
    }

    public void pfremove(String key) {
        redisTemplate.opsForHyperLogLog().delete(key);
    }

    public void pfmerge(String key1, String key2) {
        redisTemplate.opsForHyperLogLog().union(key1, key2);
    }

}

Original: https://www.cnblogs.com/aadzj/p/15636871.html
Author: 小公羊
Title: SpringBoot-Redis

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/643737/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 设计模式-策略模式

    预先定义有着不同执行过程但 结果相同的 算法族,运行时指定所需算法。 算法族此处为一组有共同主题的有相同结果的不同算法的集合。 话不多说,看个优化案例。 优化案例 不使用策略模式的…

    技术杂谈 2023年7月11日
    083
  • ThreadLocal类的一个小应用

    先前使用多线程模拟体检科室体检,但是循环使用的是while(true),一直在思考加一个线程去判断是否完成体检,然后终止这些死循环,后来发现这种idea显然绕远了。现在借助Thre…

    技术杂谈 2023年7月24日
    078
  • phpcms全文检索功能实现(集成sphinx)

    sphinx配置 sphinx是俄罗斯人开发的一个搜索引擎,基于c++编写,具有强大的检索能力,本身支持中文单个字符的检索,中文分词需要额外的插件Coreseek,但该插件已很久未…

    技术杂谈 2023年7月11日
    0137
  • spring中为类类型的属性赋值

    1 ref:引用IOC容器中的某个bean的id 2 内部bean,只能在当前bean的内部使用,不能之间通过IOC容器获取 3 级联的方式,要保证提前为clazz属性进行赋值或者…

    技术杂谈 2023年7月11日
    086
  • 人工智能算法综述 (一)

    “那一些被认作常识的东西,是不是只是时代的附属品?从整个历史的长河去看待,也许是一些莫名其妙或者残忍至极的怪事而已” 2017-2018 这两年因为一些爆炸…

    技术杂谈 2023年6月21日
    0106
  • find -exec 与多个命令

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    技术杂谈 2023年5月31日
    0107
  • 知识图谱读书笔记4

    posted @2021-10-05 11:20 DarJeely 阅读(18 ) 评论() 编辑 Original: https://www.cnblogs.com/Jeely/…

    技术杂谈 2023年5月31日
    0107
  • Upload 组件 报错 — [object File]

    博客园 :当前访问的博文已被密码保护 请输入阅读密码: Original: https://www.cnblogs.com/crazycode2/p/16538707.htmlAu…

    技术杂谈 2023年5月31日
    0104
  • Python不同数据结构的元素频率统计

    1、list的词频统计 这里利用Python字典的键值对来进行统计。逻辑就是,根据list的内容生成一个字典,把要统计的列表元素的值作为字典的key,而后给字典中对应的key进行赋…

    技术杂谈 2023年7月11日
    0103
  • 事务的隔离级别与MVCC

    提到数据库,你多半会联想到事务,进而还可能想起曾经背得滚瓜乱熟的ACID,不知道你有没有想过这个问题,事务有原子性、隔离性、一致性和持久性四大特性,为什么偏偏给隔离性设置了级别? …

    技术杂谈 2023年7月23日
    0119
  • 渗透测试过程参考

    序列号 测试漏洞 是否安全 后台路径泄露 post 注入 数据库备份 getwebshell 配置文件写入木马 任意文件上传漏洞 万能密码登陆 开源编辑器、插件漏洞 后台越权访问 …

    技术杂谈 2023年6月1日
    0110
  • HTML:2.基本结构

    HTML初识 HTML(Hyper Text Markup Language):超文本标记语言 所谓超文本,有2层含义: 它可以加入图片、声音、动画、多媒体等内容(超越文本限制 )…

    技术杂谈 2023年7月11日
    0105
  • Rust:axum学习笔记(4) 上传文件

    接上一篇继续,上传文件是 web开发中的常用功能,本文将演示axum如何实现图片上传(注:其它类型的文件原理相同),一般来说要考虑以下几个因素: 文件上传的大小限制 文件上传的类型…

    技术杂谈 2023年5月31日
    0128
  • vue-admin-template包下载地址

    https://gitee.com/panjiachen/vue-admin-template/ https://github.com/PanJiaChen/vue-admin-t…

    技术杂谈 2023年7月11日
    0116
  • find prune

    如果想查找某目录下的某些文件,但是想要避开某个目录,使用find 的-prune 但是-prune用法很严格,网上有很多文章介绍了它的用法,但是经过本人的实际使用,有些并不好用。 …

    技术杂谈 2023年6月1日
    0134
  • idea Transparent-native-to-ascii 是否需要勾选?

    首先看一下官方对该选项的解释: 第一段是说标准的Java api是用 ISO 8859-1编码 .properties文件的,所以如果你在properties文件中可以使用转义序列…

    技术杂谈 2023年7月11日
    086
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球