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框架,可以显著提高应用的性能和响应速度。

目录
相关文章
|
10月前
|
NoSQL Java Redis
springboot搭建后台框架 (二)整合Redis
springboot搭建后台框架 (二)整合Redis
88 0
|
10月前
|
NoSQL Linux Redis
Redis 的网络框架是实现了 Reactor 模型吗?
Redis 的网络框架是实现了 Reactor 模型吗?
|
10月前
|
缓存 NoSQL Java
微服务框架(十二)Spring Boot Redis 缓存
  此系列文章将会描述Java框架Spring Boot、服务治理框架Dubbo、应用容器引擎Docker,及使用Spring Boot集成Dubbo、Mybatis等开源框架,其中穿插着Spring Boot中日志切面等技术的实现。 本文为Spring Boot集成Redis。 在这篇文章中,我们将配置一个Spring Boot应用程序示例,并将其与Redis Cache 集成。虽然Redis是一个开源是一个开源内存数据结构存储,用作数据库,缓存和消息代理,但本文仅演示缓存集成。
|
10天前
|
缓存 NoSQL Java
Redis应用—8.相关的缓存框架
本文介绍了Ehcache和Guava Cache两个缓存框架及其使用方法,以及如何自定义缓存。主要内容包括:Ehcache缓存框架、Guava Cache缓存框架、自定义缓存。总结:Ehcache适合用作本地缓存或与Redis结合使用,Guava Cache则提供了更灵活的缓存管理和更高的并发性能。自定义缓存可以根据具体需求选择不同的数据结构和引用类型来实现特定的缓存策略。
Redis应用—8.相关的缓存框架
|
5月前
|
NoSQL Java Redis
redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。
这篇文章介绍了Redis的基本命令,并展示了如何使用Netty框架直接与Redis服务器进行通信,包括设置Netty客户端、编写处理程序以及初始化Channel的完整示例代码。
125 1
redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。
|
6月前
|
消息中间件 NoSQL Go
PHP转Go系列 | ThinkPHP与Gin框架之Redis延时消息队列技术实践
【9月更文挑战第7天】在从 PHP 的 ThinkPHP 框架迁移到 Go 的 Gin 框架时,涉及 Redis 延时消息队列的技术实践主要包括:理解延时消息队列概念,其能在特定时间处理消息,适用于定时任务等场景;在 ThinkPHP 中使用 Redis 实现延时队列;在 Gin 中结合 Go 的 Redis 客户端库实现类似功能;Go 具有更高性能和简洁性,适合处理大量消息。迁移过程中需考虑业务需求及系统稳定性。
128 0
|
存储 缓存 NoSQL
【缓存】J2Cache —— 基于内存和 Redis 的两级 Java 缓存框架的使用方法
【缓存】J2Cache —— 基于内存和 Redis 的两级 Java 缓存框架的使用方法
537 0
|
10月前
|
缓存 NoSQL Java
Java中操作Redis & SpringCache
Java中操作Redis & SpringCache
81 0
京东T9纯手打688页神笔记,SSM框架整合Redis搭建高效互联网应用
Spring框架是Java应用最广的框架。它的成功来源于理念,而不是技术本身,它的理念包括loC (Inversion of Control,控制反转)和AOP (Aspect Oriented Programming,面向切面编程)。
|
存储 缓存 NoSQL
分布式缓存Redis击穿、雪崩、穿透面试题+SpringCache解决方案
分布式缓存Redis击穿、雪崩、穿透面试题+SpringCache解决方案
248 0