前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Redis:SpringBoot整合Redis

Redis:SpringBoot整合Redis

原创
作者头像
GoBoy
发布2023-11-20 08:43:40
3780
发布2023-11-20 08:43:40
举报
文章被收录于专栏:GoboyGoboy

前言

Redis 的名字来源于 Remote Dictionary Server(远程字典服务器)。它是由 Salvatore Sanfilippo 在 2009 年开发的,最初是为了解决 LLOOGG 项目中的性能问题而创建的。后来,Redis 成为一个独立的开源项目,并迅速成为一种流行的内存数据库和缓存系统。

Redis 是一个开源的内存数据库和缓存系统。它被设计用于快速访问、存储和检索数据,特别是键值对(key-value pairs)。Redis 支持多种数据结构,如字符串(strings)散列(hashes)列表(lists)集合(sets)有序集合(sorted sets)与范围查询,bitmapshyperloglogs地理空间(geospatial)索引半径查询。 Redis 内置了复制(replication)LUA脚本(Lua scripting)LRU驱动事件(LRU eviction)事务(transactions)和不同级别的磁盘持久化(persistence), 并通过Redis哨兵(Sentinel)和自动分区(Cluster)提供高可用性(high availability)。

作为内存数据库,Redis 的数据存储在系统内存中,这使得它能够提供高性能的数据访问和响应速度。此外,Redis 也可以持久化数据到磁盘,以防止数据丢失。

除了作为数据库,Redis 还常被用作缓存系统,通过在内存中缓存经常访问的数据,提高应用程序的性能。

SpringBoot整合Redis

pom引入

代码语言:javascript
复制
        <!-- 引入 redis 依赖  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

yaml配置

代码语言:javascript
复制
spring:
  redis:
    database: 1
    host: 127.0.0.1
    port: 6379
    password: 123456

测试类

代码语言:javascript
复制
package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Redis 控制器
 */
@RestController
@RequestMapping("/api/redis")
public class RedisController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 设置 Redis 键值对
     *
     * @param key   键
     * @param value 值
     * @return 操作结果
     */
    @GetMapping("/set")
    public Object set(String key, String value) {
        // opsForValue() 用于操作 String 类型的数据
        redisTemplate.opsForValue().set(key, value);
        return "OK";
    }

    /**
     * 获取 Redis 值
     *
     * @param key 键
     * @return 对应的值
     */
    @GetMapping("/get")
    public Object get(String key) {
        // opsForValue() 用于操作 String 类型的数据
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除 Redis 键值对
     *
     * @param key 键
     * @return 操作结果
     */
    @GetMapping("/delete")
    public Object delete(String key) {
        // 删除 key 是通用操作
        redisTemplate.delete(key);
        return "OK";
    }
}

开始测试

代码语言:javascript
复制
http://localhost:8654/api/redis/set?key=1&value=张三
http://localhost:8654/api/redis/get?key=1
http://localhost:8654/api/redis/delete?key=1

工具类封装

代码语言:java
复制
package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

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

@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // Key 操作

    /**
     * 获取 key 的剩余过期时间
     *
     * @param key key
     * @return 剩余过期时间,单位秒
     */
    public long ttl(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 设置 key 的过期时间
     *
     * @param key     key
     * @param timeout 过期时间,单位秒
     */
    public void expire(String key, long timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * key 的自增操作
     *
     * @param key   key
     * @param delta 自增步长
     * @return 自增后的值
     */
    public long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 查找所有符合给定模式的 key
     *
     * @param pattern 模式
     * @return 符合模式的 key 集合
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 删除指定的 key
     *
     * @param key key
     */
    public void del(String key) {
        redisTemplate.delete(key);
    }

    // String 操作

    /**
     * 设置一个 key-value
     *
     * @param key   key
     * @param value value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置 key-value 和超时时间
     *
     * @param key     key
     * @param value   value
     * @param timeout 超时时间,单位秒
     */
    public void set(String key, String value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 获取 key 对应的 value
     *
     * @param key key
     * @return key 对应的 value
     */
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 批量查询 key 对应的 values
     *
     * @param keys key 列表
     * @return key 对应的 values 列表
     */
    public List<String> mget(List<String> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * 使用管道批量查询 key 对应的 values
     *
     * @param keys key 列表
     * @return key 对应的 values 列表
     */
    public List<Object> batchGet(List<String> keys) {
        return redisTemplate.executePipelined((RedisCallback<String>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            keys.forEach(src::get);
            return null;
        });
    }

    // Hash 操作

    /**
     * 将哈希表 key 中的域 field 的值设为 value
     *
     * @param key   key
     * @param field field
     * @param value value
     */
    public void hset(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 返回哈希表 key 中给定域 field 的值
     *
     * @param key   key
     * @param field field
     * @return 哈希表中指定域的值
     */
    public String hget(String key, String field) {
        return (String) redisTemplate.opsForHash().get(key, field);
    }

    /**
     * 删除哈希表 key 中的指定域
     *
     * @param key    key
     * @param fields fields
     */
    public void hdel(String key, Object... fields) {
        redisTemplate.opsForHash().delete(key, fields);
    }

    /**
     * 返回哈希表 key 中所有的域和值
     *
     * @param key key
     * @return 哈希表中所有的域和值
     */
    public Map<Object, Object> hgetall(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    // List 操作

    /**
     * 将一个值插入到列表 key 的表头
     *
     * @param key   key
     * @param value value
     * @return 执行 LPUSH 命令后,列表的长度。
     */
    public long lpush(String key, String value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 移除并返回列表 key 的头元素
     *
     * @param key key
     * @return 列表 key 的头元素。
     */
    public String lpop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 将一个值插入到列表 key 的表尾
     *
     * @param key   key
     * @param value value
     * @return 执行 LPUSH 命令后,列表的长度。
     */
    public long rpush(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }
}

工具测试类

代码语言:javascript
复制
package com.example.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Redis 控制器
 */
@RestController
@RequestMapping("/api/rrredis")
public class Redis2Controller {

    @Autowired
    private RedisUtil redisOperator;

    /**
     * 设置 Redis 键值对
     *
     * @param key   键
     * @param value 值
     * @return 操作结果
     */
    @GetMapping("/set")
    public String set(String key, String value) {
        redisOperator.set(key, value);
        return "OK";
    }

    /**
     * 获取 Redis 值
     *
     * @param key 键
     * @return 对应的值
     */
    @GetMapping("/get")
    public Object get(String key) {
        return redisOperator.get(key);
    }

    /**
     * 删除 Redis 键值对
     *
     * @param key 键
     * @return 操作结果
     */
    @GetMapping("/delete")
    public String delete(String key) {
        redisOperator.del(key);
        return "OK";
    }
}

我正在参与2023腾讯技术创作特训营第三期有奖征文,组队打卡瓜分大奖!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • SpringBoot整合Redis
    • pom引入
      • yaml配置
        • 测试类
          • 开始测试
            • 工具类封装
              • 工具测试类
              相关产品与服务
              云数据库 Redis
              腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档