Redis的操作以及SpringCache框架

简介: 以及如何在Spring Boot应用中使用Spring Cache框架集成Redis。Redis提供了丰富的数据结构和高效的内存存储能力,结合Spring Cache框架,可以显著提高应用的性能和响应速度。

Redis的操作以及Spring Cache框架

Redis是一种开源的内存数据结构存储,用作数据库、缓存和消息代理。它支持多种数据结构,如字符串、哈希、列表、集合、有序集合等。在Spring应用中,可以使用Spring Cache框架结合Redis来实现高效的缓存机制。本文将详细介绍Redis的基本操作以及如何在Spring Boot中使用Spring Cache框架集成Redis。

一、Redis的基本操作

1.1 字符串操作

设置键值对

SET key value
​

示例:

SET myKey "Hello, Redis!"
​

获取值

GET key
​

示例:

GET myKey
​

1.2 哈希操作

设置哈希值

HSET key field value
​

示例:

HSET myHash field1 "value1"
​

获取哈希值

HGET key field
​

示例:

HGET myHash field1
​

1.3 列表操作

向列表左侧推入值

LPUSH key value
​

示例:

LPUSH myList "value1"
​

从列表右侧弹出值

RPOP key
​

示例:

RPOP myList
​

1.4 集合操作

向集合添加值

SADD key member
​

示例:

SADD mySet "member1"
​

获取集合中的所有值

SMEMBERS key
​

示例:

SMEMBERS mySet
​

1.5 有序集合操作

向有序集合添加值

ZADD key score member
​

示例:

ZADD myZSet 1 "member1"
​

获取有序集合中的值

ZRANGE key start stop
​

示例:

ZRANGE myZSet 0 -1
​

二、Spring Cache框架集成Redis

2.1 引入依赖

pom.xml中添加Spring Boot和Redis的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
​

2.2 配置Redis连接

application.ymlapplication.properties中配置Redis连接信息:

spring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword # 如果没有设置密码,可以省略
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
​

2.3 启用缓存支持

在Spring Boot的主应用类上启用缓存支持:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
​

2.4 配置缓存管理器

创建一个配置类,用于配置Redis缓存管理器:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.redis.RedisCacheConfiguration;
import org.springframework.cache.redis.RedisCacheManager;
import org.springframework.cache.redis.RedisCacheWriter;
import org.springframework.cache.redis.connection.RedisConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(60)); // 设置缓存过期时间

        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }
}
​

2.5 使用缓存注解

在需要缓存的方法上使用缓存注解,Spring提供了 @Cacheable@CachePut@CacheEvict等注解,方便地进行缓存操作。

2.5.1 @Cacheable

@Cacheable注解用于将方法的返回结果缓存起来,缓存的键由方法参数组成。

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Cacheable(value = "users", key = "#userId")
    public User getUserById(String userId) {
        // 模拟从数据库中获取用户信息
        return new User(userId, "John Doe", "john@example.com");
    }
}
​

2.5.2 @CachePut

@CachePut注解用于更新缓存,不影响方法的执行。

import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @CachePut(value = "users", key = "#user.id")
    public User updateUser(User user) {
        // 模拟更新数据库中的用户信息
        return user;
    }
}
​

2.5.3 @CacheEvict

@CacheEvict注解用于清除缓存,通常在删除或更新操作时使用。

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @CacheEvict(value = "users", key = "#userId")
    public void deleteUserById(String userId) {
        // 模拟从数据库中删除用户信息
    }
}
​

三、示例项目

以下是一个完整的示例项目,展示了如何在Spring Boot中使用Redis进行缓存操作。

3.1 项目结构

├── src
│   ├── main
│   │   ├── java
│   │   │   ├── com
│   │   │   │   ├── example
│   │   │   │   │   ├── Application.java
│   │   │   │   │   ├── CacheConfig.java
│   │   │   │   │   ├── UserService.java
│   │   ├── resources
│   │   │   ├── application.yml
​

3.2 代码实现

Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
​

CacheConfig.java

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.redis.RedisCacheConfiguration;
import org.springframework.cache.redis.RedisCacheManager;
import org.springframework.cache.redis.RedisCacheWriter;
import org.springframework.cache.redis.connection.RedisConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
public class CacheConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(60)); // 设置缓存过期时间

        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }
}
​

UserService.java

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Cacheable(value = "users", key = "#userId")
    public User getUserById(String userId) {
        // 模拟从数据库中获取用户信息
        return new User(userId, "John Doe", "john@example.com");
    }

    @CachePut(value = "users", key = "#user.id")
    public User updateUser(User user) {
        // 模拟更新数据库中的用户信息
        return user;
    }

    @CacheEvict(value = "users", key = "#userId")
    public void deleteUserById(String userId) {
        // 模拟从数据库中删除用户信息
    }
}
​

application.yml

spring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword # 如果没有设置密码,可以省略
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
​

四、总结

通过本文的介绍,我们详细讲解了Redis的基本操作

以及如何在Spring Boot应用中使用Spring Cache框架集成Redis。Redis提供了丰富的数据结构和高效的内存存储能力,结合Spring Cache框架,可以显著提高应用的性能和响应速度。

目录
相关文章
|
9月前
|
NoSQL Java Redis
SpringBoot 配置Redis操作
SpringBoot 配置Redis操作
84 0
|
6月前
|
SQL NoSQL Go
怎么用redigo操作redis?
本文介绍了使用Go语言的`redigo`库操作Redis数据库的方法。`redigo`支持Redis的所有命令,可通过`go get github.com/gomodule/redigo/redis`安装。文章详细讲解了如何建立Redis连接、执行基本的字符串操作(如设置与获取键值)、设置键值过期时间、判断键值是否存在等,并进一步演示了对Redis的数据结构如List、Set、Hash及ZSet的操作方法。此外,还提供了使用连接池以提升性能的示例。值得注意的是,`redigo`自身并不支持Redis集群功能,如需使用需引入额外的库。
102 1
|
存储 JSON NoSQL
Redis-使用java代码操作Redis->java连接上redis,java操作redis的常见类型数据存储,redis中的项目应用
Redis-使用java代码操作Redis->java连接上redis,java操作redis的常见类型数据存储,redis中的项目应用
117 0
|
消息中间件 监控 NoSQL
你不知道的redis五-redis进阶,第三方jar没有封装的命令我们该怎么执行?
你不知道的redis五-redis进阶,第三方jar没有封装的命令我们该怎么执行?
141 0
|
NoSQL Java Redis
Springboot集成redis和解决redis key乱码问题
今天在使用springboot整合redis时出现序列化乱码的问题,所以记录一下
887 0
|
缓存 NoSQL Java
SpringCache掌握及操作Redis
是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能,大大简化我们在业务中操作缓存的代码。Spring Cache只是提供了一层抽象,底层可以切换不同的cache实现。具体就是通过接口来统一不同的缓存技术。CacheManager是Spring提供的各种缓存技术抽象接口。描述使用EhCache作为缓存技术使用Google的GuavaCache作为缓存技术使用Redis作为缓存技术。
134 0
SpringCache掌握及操作Redis
|
NoSQL Java Redis
(Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
(Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
925 1
(Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
|
缓存 NoSQL 网络协议
利用Java来访问Redis并对Redis进行相关操作以及spring+redis集成配置与注解式注解
redis缓存的一些注意事项 只应将热数据放到缓存中 所有缓存信息都应设置过期时间 缓存过期时间应当分散以避免集中过期 缓存key应具备可读性 应避免不同业务出现同名缓存key 可对key进行适当的缩写以节省内存空间 选择合适的数据结构 确保写入缓存中的数据是完整且正确的 避免使用耗时较长的操作命令,如:keys * Redis默认配置中操作耗时超过10ms即视为慢查询 一个key对应的数据不应过大 对于string类型,一个key对应的value大小应控制在10K以内,1K左右更优hash类型,不应超过5000行
|
NoSQL Java fastjson
SpringBoot下用Kyro作为Redis序列化工具
有时候我们需要将Java对象实例存入Redis,常用方法有两种: 1. 将对象序列化成字符串后存入Redis; 2. 将对象序列化成byte数组后存入Redis;有关这两种存储方式的性能对比,会在下一章通过实战验证,本章先来看一下如何将对象序列化成byte数组后存入Redis;
563 0
SpringBoot下用Kyro作为Redis序列化工具
|
缓存 JSON NoSQL
[Springboot]SpringCache + Redis实现数据缓存
本文实现了SpringCache + Redis的集中式缓存,方便大家对学习了解缓存的使用。 本文实现: SpringCache + Redis的组合 通过配置文件实现了自定义key过期时间;key命名方式;value序列化方式 实现本文代码的前提: 已有一个可以运行的Springboot项目,实现了简单的CRUD功能
253 0