【spring-boot】配置Redis工具类

如何在spring-boot中使用Redis工具类

修改pom.xml文件

新增spring-boot-starter-data-redis配置

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

修改application.yml

新增Redis配置

server:
  port: 6660
  redis:
    host: 127.0.0.1
    port: 6379
    password:

新增config目录

RedisConfig.java文件

package com.example.redisdemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author komiles@163.com
 * @date 2020-05-22 14:40
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    /**
     * 实例化redisTempate对象
     * primary 在autowired时,优先选择我注册的bean
     * 因为在redis 框架中有注册一个StringRedisTemplate,避免注入冲突
     * @return
     */
    @Bean
    @Primary
    public RedisTemplate RedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate<>();
        initRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;

    }

    /**
     * 设置数据存入Redis的序列化方式
     * @param redisTemplate
     * @param factory
     */
    private void initRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
    }
}

新增RedisUtil.java文件

package com.example.redisdemo.util;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * @author komiles@163.com
 * @date 2020-05-22 15:31
 */
@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    // =============================common============================
    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    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;
        }
    }

    /**
     * 根据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(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)
     * @return
     */
    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)
     * @return
     */
    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
     * @return 值
     */
    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 对应多个键值
     * @return true 成功 false 失败
     */
    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) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            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) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            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)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

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

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    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, 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;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    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代表所有值
     * @return
     */
    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 键
     * @return
     */
    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*/
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

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

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    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;
        }
    }

    /**
     * 将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) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            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;
        }
    }
},>,>,>,object>

新增Test2Controller.java

package com.example.redisdemo.controller;

import com.example.redisdemo.dao.Person;
import com.example.redisdemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author komiles@163.com
 * @date 2020-05-22 15:13
 */

@RestController
@RequestMapping("/test2")
public class Test2Controller {

    static final String USER_LIST_HASH_KEY = "student_list_0522_02";

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/set")
    public String setStr(@Param("key") String key, @Param("value") String value){
        redisUtil.set(key,value);
        return key;
    }

    @GetMapping("/get")
    public String setStr(@Param("key") String key){
        return redisUtil.get(key).toString();
    }

    @GetMapping("/hashSet")
    public String setHash(){
        Person person = new Person();
        person.setId("1").setName("张三");
        redisUtil.hset(USER_LIST_HASH_KEY,person.getId(),person);
        return "OK";
    }

    @GetMapping("/hashGet")
    public Object getHash(){
        Person person = new Person();
        person.setId("1").setName("张三");
        return redisUtil.hget(USER_LIST_HASH_KEY,"1");
    }
}

新增实体类 Person.java

用来测试

package com.example.redisdemo.dao;

import java.io.Serializable;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @author komiles@163.com
 * @date 2020-05-22 15:11
 */
@Data
@Accessors(chain = true)
public class Person implements Serializable {

    private static final Long serialVersionUID = 99999L;

    private String id;

    private String name;
}

调用controller.java

项目demo地址

Original: https://www.cnblogs.com/wangkongming/p/12938709.html
Author: KoMiles
Title: 【spring-boot】配置Redis工具类

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

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

(0)

大家都在看

  • 吴军《浪潮之巅》阅读随笔(二)信息产业的规律性

    在这本书上册的最后一章《信息产业的规律性》中,有几个问题让我很感兴趣。 在信息科技某个领域发展成熟之后,一般在全球容不下三个以上的主要竞争者,这个行业一定有一个老大、是这个行业的主…

    Linux 2023年6月14日
    0136
  • aspx页面,后端通过Attributes.Add给textbox添加事件时,传参失效问题。

    测试一:————————————&#…

    Linux 2023年6月7日
    0101
  • 驳”一切不谈考核的管理都是扯淡”

    一、引子 以我个人的从业经验认为,研发人员的量化考核,始终是一个世界难题。正巧不久前在园子里看到了 “一切不谈考核的管理都是扯淡!”一文(下面简称为&#82…

    Linux 2023年6月13日
    093
  • Android recovery支持adb shell

    Android recovery支持adb shell 近期开发过程注意到recovery不支持adb shell。为了便于调试方便,决定添加此功能。 刚開始我们採用的是user版…

    Linux 2023年5月28日
    0105
  • 从前端走向后端

    每次过年回老家聚会,遇到不熟悉的亲戚朋友,经常被问到职业是什么。一开始,我总是很认真的回答这个问题,结果常常引出一番尴尬的问答。 &#x201C;&#x4F60;&…

    Linux 2023年6月6日
    0103
  • Docker基本命令

    第一次使用docker,从helle world开始 docker run hello-world 镜像的完整写法:[仓库地址/]镜像名[:版本号] –help 查看帮…

    Linux 2023年6月13日
    0110
  • Docker如何镜像加速

    原文链接:https://www.zhoubotong.site/post/69.html在使用Docker 下载镜像时,如果不配置镜像加速,下载镜像会比较慢,因为国内从 Dock…

    Linux 2023年6月6日
    0143
  • Linux下出现Permission denied解决

    输入命令设置root密码 sudo passwd 得到的答复是 We trust you have received the usual lecture from the loca…

    Linux 2023年6月14日
    095
  • C++的回调函数

    一、简介 本文主要介绍C++中如何使用回调函数。 二、回调函数介绍 回调函数主要在”回”字,和正常的函数调用方式不太一样。正常的函数由开发者自己定义返回类型…

    Linux 2023年6月7日
    0106
  • Django中orm的双重方法

    orm中的双重方法 更新或创建 Draw2DDevice.objects.update_or_create( defaults={‘x’: 777, ‘y’: 777,}, dev…

    Linux 2023年6月14日
    081
  • prometheus监控redis集群

    【1】利用 redis_exporter 监控 redis 集群 (1.0)redis_exporter 以前都是用傻办法,一个实例一个采集器; redis_exporter 支持…

    Linux 2023年5月28日
    0108
  • 事务与事务隔离级别详解

    事务基本概念 一组要么同时执行成功,要么同时执行失败的SQL 语句。是数据库操作的一个执行单元。 事务开始于: 连接到数据库上,并执行一条DML 语句in sert 、update…

    Linux 2023年6月14日
    0101
  • 【Example】C++ std::thread 及 std::mutex

    与 Unix 下的 thread 不同的是,C++ 标准库当中的 std::thread 功能更加简单,可以支持跨平台特性。 因此在项目需要跨平台及对多线程简单应用情况下,应优先考…

    Linux 2023年6月13日
    065
  • 安卓投屏助手(ARDC)最新版

    近几年安卓多屏协同非常火爆,以华为小米为首的各大手机厂商都推出了各自的多屏协同软件,打破手机、平板和VR等安卓设备与电脑的边界,通过多屏融合提高办公的生产力。国内安卓投屏软件有To…

    Linux 2023年6月7日
    0329
  • 使用VScode创建第一个vue项目

    初识vue,小小白一枚 软件,插件安装,略… 插件:vetur(支持vue代码高亮)、ESLint(js语法纠错)、Auto Close Tag(自动闭合标签)、Aut…

    Linux 2023年6月7日
    0103
  • 脚本安装lamp

    脚本安装lamp [root@localhost ~]# mkdir lamp [root@localhost ~]# cd lamp/ [root@localhost lamp]…

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