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)

大家都在看

  • 一篇理解什么是CanSet, CanAddr?

    什么是可设置( CanSet ) 首先需要先明确下,可设置是针对 reflect.Value 的。普通的变量要转变成为 reflect.Value 需要先使用 reflect.Va…

    技术杂谈 2023年6月1日
    0111
  • centos磁盘满

    1、使用命令:df -lk 找到已满磁盘 2、使用命令:du –max-depth=1 -h 查找大文件,删除 Original: https://www.cnblog…

    技术杂谈 2023年7月24日
    069
  • 规范浅谈

    代码规范这东西网上很容易百度到一堆,除了天下文章一大抄的问题,另外,多数只给了结果,原因没有充分说明,或者非常的纠结于大写小写,一个函数可以写几行的细节。感觉有点容易让新人误入歧途…

    技术杂谈 2023年5月31日
    089
  • HugeGraph入门

    前言 下载链接 链接:https://pan.baidu.com/s/1P7eIelXHI0l5pSEBFCCF7Q提取码:vax4 一、HugeGraph简介 最近在搞好友推荐方…

    技术杂谈 2023年6月1日
    0112
  • 并发编程基础(上)

    从我开始写博客到现在,已经写了不少关于并发编程的了,差不多还有一半内容整个并发编程系列就结束了,而今天这篇博客是比较简单的,只是介绍下并发编程的基础知识( = =!其实,对于大神来…

    技术杂谈 2023年7月25日
    068
  • 老杜带你学Ajax,轻松掌握ajax底层实现原理

    课程导读 原生的ajax虽然在实际开发中很少编写,但如果想将js高级框架底层学明白,那ajax的原理是必须要求精通的。 本套ajax视频对ajax底层实现原理讲解非常透彻,对aja…

    技术杂谈 2023年7月25日
    095
  • Debian 9.4 安装教程

    我们这里选择install安装,不装桌面,因为是做服务器,装桌面没意义。 我们这里选择装英文版,你也可以装中文版本。 手动配置网络-manually 设置IP 设置 子网掩码 设置…

    技术杂谈 2023年7月10日
    077
  • 手把手教你用JAVA实现“语音识别”功能(声音转文字)标贝科技

    手把手教你用JAVA实现”语音识别”功能(声音转文字)标贝科技 前言 什么是语音识别?将自然语音转换为文本信息,本篇文章将介绍”一句话识别&#8…

    技术杂谈 2023年7月25日
    086
  • 一文搞懂│XSS攻击、SQL注入、CSRF攻击、DDOS攻击、DNS劫持

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

    技术杂谈 2023年7月11日
    097
  • 前端

    https://www.made-in-china.com/ Original: https://www.cnblogs.com/hshy/p/16536327.htmlAutho…

    技术杂谈 2023年5月31日
    097
  • JSON数据传输大法第一式——用OADate处理日期格式

    JSON作为一种轻量级的数据交换格式,通常采用完全独立于编程语言的文本格式来存储和表示数据。它的层次结构简洁清晰,易于人们的阅读和编写,此外机器编写和生成也会变得容易,可以有效地提…

    技术杂谈 2023年5月30日
    0132
  • NoteOfMySQL-13-事务与并发控制

    一、事务简介 存储引擎如InnoDB、BDB才支持事务处理。 每个事务(transaction)的处理必须满足ACID原则: 原子性(Atomicity): 原子性指每个事务都必须…

    技术杂谈 2023年7月11日
    0108
  • 「游记」NOIP2021爆零记

    欧拉欧拉欧拉欧拉欧拉欧拉欧拉欧拉,第一次参加 (NOIP),欧拉欧拉欧拉欧拉欧拉欧拉欧拉欧拉。 第一题比较简单,用类似于筛质数的做法即可,鉴于 CSP-S 的 (T1) 写挂,这从…

    技术杂谈 2023年7月24日
    067
  • Redis做Mybatis的二级缓存

    基于spring boot项目的前提下,使用redis数据库做mybatis的二级缓存。 Redis做mybatis的二级缓存 作用提升速度,保证多台服务器访问同一数据库时不会崩注…

    技术杂谈 2023年7月11日
    079
  • 2.Add Two Numbers——LeetCode

    You are given two non-empty linked lists representing two non-negative integers. The digit…

    技术杂谈 2023年6月21日
    077
  • Xamarin 跨移动端开发系列(01) — 搭建环境、编译、调试、部署、运行

    (本文是基于老版本的VS和Xamarin,而VS2017已经集成了Xamarin,所以,本文已经过时,最新的Xamarin开发介绍请参见 使用 Xamarin开发手机聊天程序 。)…

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