总结 redis缓存在增删改中的应用示例
add:添加成功,清理缓存; update:修改成功,清理缓存; del:删除成功,清理缓存; get:查询列表,先从缓存中取数据,缓存中数据为空再从数据库读取数据;
适用范围,数据量小且不经常变动的数据,利用缓存读写分离,减轻数据库压力,提高效率
/** * 自定义应用dao层实现层 */ @Repository("iApplicationCustomizeDao") public class ApplicationCustomizeDaoImpl extends BaseDaoMybatis implements IApplicationCustomizeDao { @Override public ApplicationCustomize add(ApplicationCustomize app) throws Exception { RedisClient redisClient = new RedisClient(CacheKey.PREFIX_APPLICATION_CUSTOMIZE); app.setId(ConfigUtil.getSeqNo()); app.setType(1); app.setSupportAndroid(0); app.setSupportWeb(0); app.setSupportIos(0); log.debug("新增应用,app={}", app); if(this.insert("APP_CUSTOMIZE.add", app) > 0){ // 清理对应缓存 redisClient.deleteObject(app.getCompanyId()); return app; } return null; } @Override public int removeById(String companyId, String appId) { RedisClient redisClient = new RedisClient(CacheKey.PREFIX_APPLICATION_CUSTOMIZE); if(this.delete("APP_CUSTOMIZE.removeById", appId) > 0){ // 清理对应缓存 redisClient.deleteObject(companyId); return 1; } return 0; } @Override public List<ApplicationCustomize> findListByCompanyId(String companyId) { log.debug("查询应用列表,参数companyId={}", companyId); RedisClient redisClient = new RedisClient(CacheKey.PREFIX_APPLICATION_CUSTOMIZE); // 从缓存中取值 List<ApplicationCustomize> list = null; Object json = redisClient.findObject(companyId); if(json == null || "".equals(json)){ // 查询不到搜索数据库,并将结果放入缓存 list = this.queryList("APP_CUSTOMIZE.findListByCompanyId", companyId); if(!CollectionUtils.isEmpty(list)){ redisClient.saveObject(companyId, JacksonUtil.toJson(list), Constants.TIMEOUT_2D); } }else{ list = JacksonUtil.listFromJson(json.toString(), ApplicationCustomize.class); } return list; } @Override public ApplicationCustomize findById(String companyId, String appId) { log.debug("根据企业id和appId查询指定自定义应用,参数companyId={},appId={}", companyId, appId); List<ApplicationCustomize> list = this.findListByCompanyId(companyId); if(!CollectionUtils.isEmpty(list)){ for (ApplicationCustomize app : list) { if(appId.equals(app.getId())){ return app; } } } return null; } @Override public ApplicationCustomize findByName(String companyId, String name) { log.debug("根据企业id和名称查询指定自定义应用,参数companyId={},name={}", companyId, name); List<ApplicationCustomize> list = this.findListByCompanyId(companyId); if(!CollectionUtils.isEmpty(list)){ for (ApplicationCustomize app : list) { if(name.equals(app.getName())){ return app; } } } return null; } @Override public int update(ApplicationCustomize app) { RedisClient redisClient = new RedisClient(CacheKey.PREFIX_APPLICATION_CUSTOMIZE); if(this.update("APP_CUSTOMIZE.update", app) > 0){ redisClient.deleteObject(app.getCompanyId()); return 1; } return 0; } }
雨淋淋过的季节

浙公网安备 33010602011771号