在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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值