SpringBoot 开启Redis缓存及使用方法

SpringBoot整合Redis缓存,通过简单配置即可启用,支持常规缓存操作,提高应用性能。

全面解析SpringBoot整合Redis:开启缓存并掌握使用方法

概述

在当今的互联网时代,数据的高效访问和存储是提升应用性能的关键因素,缓存技术作为一种优化手段,可以有效减少数据库的访问次数,提高系统的响应速度,Redis作为一款高性能的key-value存储系统,广泛应用于缓存场景,SpringBoot作为流行的Java Web开发框架,与Redis的整合变得尤为简单,本文将详细介绍如何在SpringBoot项目中开启Redis缓存及使用方法。

SpringBoot 开启Redis缓存及使用方法

环境准备

1、安装Redis:确保本地或服务器已安装Redis,并启动Redis服务。

2、创建SpringBoot项目:使用Spring Initializr创建一个SpringBoot项目,添加Web、Redis依赖。

配置Redis

1、在application.properties或application.yml文件中配置Redis服务信息:

application.properties
spring.redis.host=localhost  # Redis服务器地址
spring.redis.port=6379       # Redis服务器端口
spring.redis.password=       # Redis服务器密码(如无密码,可不配置)
spring.redis.database=0      # Redis数据库索引(默认为0)

2、在SpringBoot项目中创建Redis配置类,用于配置RedisTemplate和StringRedisTemplate:

SpringBoot 开启Redis缓存及使用方法

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 设置key的序列化策略
        template.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化策略
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 设置hash key和value的序列化策略
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 必须执行这个函数,初始化RedisTemplate
        template.afterPropertiesSet();
        return template;
    }
}

开启缓存

1、在SpringBoot启动类上添加@EnableCaching注解,开启缓存功能:

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、在需要使用缓存的方法上添加@Cacheable、@CachePut、@CacheEvict等注解,实现缓存操作。

缓存使用方法

1、@Cacheable:表示该方法的结果可以被缓存,当方法被调用时,Spring会检查指定的缓存中是否已存在相应的结果,如果存在,则返回缓存的结果,否则执行方法并缓存结果。

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @Cacheable(value = "user", key = "#id")
    public User findById(Long id) {
        // 模拟数据库查询操作
        return new User(id, "张三");
    }
}

2、@CachePut:表示该方法的结果会被更新到缓存中,无论方法是否被调用,都会将方法的返回结果更新到指定的缓存中。

SpringBoot 开启Redis缓存及使用方法

import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @CachePut(value = "user", key = "#user.id")
    public User updateUser(User user) {
        // 模拟数据库更新操作
        return user;
    }
}

3、@CacheEvict:表示从缓存中移除指定key的数据。

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @CacheEvict(value = "user", key = "#id")
    public void deleteUser(Long id) {
        // 模拟数据库删除操作
    }
}

4、@Caching:用于在一个方法上组合多个缓存操作。

import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @Caching(
        cacheable = @Cacheable(value = "user", key = "#id"),
        put = @CachePut(value = "user", key = "#user.id"),
        evict = @CacheEvict(value = "user", key = "#id")
    )
    public User updateUser(User user, Long id) {
        // 模拟数据库查询、更新操作
        return user;
    }
}

本文详细介绍了SpringBoot项目中开启Redis缓存及使用方法,通过整合Redis,我们可以轻松实现数据的缓存操作,提高系统的性能和响应速度,在实际开发中,根据业务需求选择合适的缓存策略,可以大大提高系统的用户体验,希望本文对您有所帮助。

原创文章,作者:酷盾叔,如若转载,请注明出处:https://www.kdun.com/ask/237375.html

(0)
酷盾叔订阅
上一篇 2024-02-19 12:18
下一篇 2024-02-19 12:33

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入