SpringBoot整合MongoDB(实现一个简单缓存) (3)

缓存中的数据和存储的关系数据库的数据是一致的,当我们只有查询操作的时候,可以一直保持数据的一致性,但是我们如果对数据有更新、删除的操作,就需要对关系数据库和MongoDB中的数据同时进行更新或删除的操作,让数据再次达到一致性的效果。

缓存更新

虽然大部分情况我们对热点新闻数据可能很少更新,但是也有时候新闻中有部分内容需要更改的需要我们完成,比如比分错字或者不妥的言论。

我们在NewsService中编写updateNewsContentByTitle((String title,String content)函数,其作用为更新数据库(这里没有具体实现)和MongoDB缓存中的数据:

public boolean updateNewsContentByTitle(String title,String content) { try { Query query = new Query(Criteria.where("title").is(title)); Update update = new Update(); update.set("content", content);//更新内容 update.set("date",new Date());//更新时间 // 假设在这里数据库中更新过这里跳过 // updateFirst 更新查询返回结果集的第一条 //upsert 更新如果不存在就插入 mongoTemplate.upsert(query, update, news.class); } catch (Exception e) { return false; } return true; }

其中:

Query对象来辅助我们实现条件查询待更新数据,这里的意思就是查询条件同样为:MongoDB中title字段为传进来title字符串的该条记录。

Update对象用来记录更新的字段和数据,这里更新传进来的content内容和date日期。

mongoTemplate.upsert(query, update, news.class)用来实现更新,如果MongoDB中不存在该数据那么就插入到MongoDB中。

编写完service,在newsController中编写一个名为updatenews的接口,用来更新数据库数据和缓存在MongoDB的数据:

@GetMapping("updatenews") public String updatenews(String title,String content) { boolean bool=newsService.updateNewsContentByTitle(title,content); if(bool) return "更新成功"; else return "更新失败"; }

启动程序访问localhost:8080/updatenews?title=好好学java&content=学好java走遍全天下,你会发现数据更新成功:

在这里插入图片描述

缓存删除

除了更新的时候需要保证数据一致性,删除的时候也需要保证数据一致性,如果在删除关系数据库的数据而不删除MongoDB缓存,那么下次查询该条数据MongoDB中存在而关系数据库中不存在,这样就造成了数据不一致,所以在删除数据的时候我们需要在MongoDB中的数据也删除。

在NewsService中编写deleteNewsByTitle(String title)函数,用来根据标题title删除MongoDB中的记录:

public boolean deleteNewsByTitle(String title) { try { Query query = new Query(Criteria.where("title").is(title)); mongoTemplate.remove(query,news.class); } catch (Exception e) { return false; } return true; }

mongoTemplate.remove(query,news.class);意味从MongoDB中删除满足查询条件的记录。其中query为查询条件,news.class为删除对象在Java中的类。

在newsController中编写deletenews接口,用来处理删除的请求:

@GetMapping("deletenews/{title}") public String deletenews(@PathVariable String title) { try { newsService.deleteNewsByTitle("好好学java"); return "删除成功"; } catch (Exception e) { return "删除失败"; } }

启动程序,访问:8080/deletenews/好好学java,会发现缓存在MongoDB中的记录被成功删除,这样就保证MongoDB中不会出现关系数据库中不存在的脏数据,达到数据一致性!

在这里插入图片描述

本篇到这里就结束了,如果帮助还请不要吝啬你的小赞、收藏一份如有更多期待还请关注公众号bigsai,回复bigsai获取珍藏pdf资源一份!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyxdz.html