在redis取数据若存在直接取,不存在在db中取,并放到缓存中

我们经常把一些常用的数据存放到redis中,以提高查询效率,对于springboot项目可以用标签注释的方式进行在redis中取数据,即先查缓存(redis),若不存在就查询数据库,并把查到的值放入到redis中。主要应用两个标签@CacheConfig ,@Cacheable

接口

标签在接口中进行注解。

import com.bot.model.BotConfig;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;


@CacheConfig(cacheNames="BOT:BAIDU:CONFIG")
public interface IBotConfigSevice {
    /**
     * 进行token验证,先查redis不存在时在访问db,把db中的数据存入缓存
     * @param token
     * @return
     */
    @Cacheable(key="targetClass+':'+methodName+':'+args")
    BotConfig getBotConfig(String token);
}

接口实现类

import com.alibaba.fastjson.JSON;
import com.base.service.support.BaseService;
import com.bot.model.BotConfig;
import com.bot.service.IBotConfigSevice;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class BotConfigService implements IBotConfigSevice {

    @Override
    public BotConfig getBotConfig(String token) {
        String sql = "select * from te_bot_config where token=?";
        Map map = this.db1JdbcDaoSupport.queryForMap(sql, token);
        BotConfig botConfig= JSON.parseObject(JSON.toJSONString(map), BotConfig.class);
        return botConfig;
    }
}

注意可以使用JSON.parseObject(JSON.toJSONString(map), BotConfig.class);将一个Map的数据赋值给实体类。

接口调用

在项目的拦截器或者其他什么地方调用接口就可以实现先查缓存(redis),若不存在就查询数据库,并把查到的值放入到redis中。可以减少我们自己进行缓存处理工作。

public class BotCatchService implements IBotCatchService {
    @Resource
    private IBotConfigSevice iBotConfigSevice;
    
    public BotConfig getBotInfo(String token) {
        return iBotConfigSevice.getBotConfig(token);
    }
}
在 Spring Boot 应用中将数据存储到 Redis 缓存可以通过多种方式实现,主要依赖于 Spring Data Redis 提供的功能。以下是几种常见的实现方法: ### 1. 使用 `RedisTemplate` 操作 Redis 缓存 `RedisTemplate` 是 Spring Data Redis 提供的核心类,可以用于操作 Redis 中的各种数据类型。例如,将字符串数据存储到 Redis 中: ```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; @Service public class RedisService { @Resource private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value, long timeout, TimeUnit unit) { redisTemplate.opsForValue().set(key, value, timeout, unit); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } } ``` 此方法提供了对 Redis 缓存的细粒度控制,适用于需要灵活操作缓存数据的场景[^4]。 --- ### 2. 使用 `@Cacheable`、`@CachePut` 和 `@CacheEvict` 注解 Spring Boot 提供了基于注解的缓存支持,可以简化缓存操作。例如,使用 `@Cacheable` 注解缓存方法返回的数据: ```java import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class CacheService { @Cacheable(value = "data", key = "#id") public String getData(String id) { // 模拟从数据库中获数据 return "Data from DB: " + id; } } ``` 上述代码中,`@Cacheable` 注解会自动将方法的返回值缓存Redis 中,使用 `id` 作为缓存的键。当再次调用该方法时,Spring 会接从缓存中获数据,而会执行方法体[^2]。 此外,`@CachePut` 用于更新缓存,而 `@CacheEvict` 用于清除缓存。例如: ```java @CachePut(value = "data", key = "#id") public String updateData(String id, String newData) { return newData; } @CacheEvict(value = "data", key = "#id") public void deleteData(String id) { // 删除缓存中的数据 } ``` 这些注解可以极大地简化缓存操作,适用于需要快速实现缓存功能的场景[^1]。 --- ### 3. 配置 Redis 缓存管理器 为了支持基于注解的缓存功能,需要配置 `RedisCacheManager`。以下是配置示例: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; @Configuration public class RedisCacheConfig { @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) .entryTtl(Duration.ofMinutes(10)); // 设置缓存过期时间为10分钟 return RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); } } ``` 通过配置 `RedisCacheManager`,可以设置缓存的序列化方式和过期时间等参,从而更好地控制缓存行为[^3]。 --- ### 4. 配置 Redis 连接信息 在 `application.yml` 或 `application.properties` 文件中配置 Redis 的连接信息。例如: ```yaml spring: redis: host: localhost port: 6379 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 2 max-wait: 2000ms timeout: 5000ms ``` 上述配置指定了 Redis 服务器的地址、端口以及连接池的相关参,确保应用能够高效地与 Redis 交互[^4]。 --- ### 5. 使用通用工具类封装 Redis 操作 为了简化 Redis 操作,可以将常用的 Redis 操作封装成一个通用工具类。例如: ```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; @Component public class RedisUtil { @Resource private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value, long timeout, TimeUnit unit) { redisTemplate.opsForValue().set(key, value, timeout, unit); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void delete(String key) { redisTemplate.delete(key); } public boolean expire(String key, long timeout, TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); } } ``` 通过封装工具类,可以提高代码的复用性,简化 Redis 操作的实现[^1]。 --- ### 总结 在 Spring Boot 应用中,可以通过 `RedisTemplate` 接操作 Redis 缓存,也可以使用基于注解的缓存功能(如 `@Cacheable`、`@CachePut` 和 `@CacheEvict`)。同时,还可以通过配置 `RedisCacheManager` 来管理缓存行为,通过通用工具类封装 Redis 操作,从而提高开发效率。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值