我们经常把一些常用的数据存放到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);
}
}