preface
SpringBoot is commonly used development framework, and MongoDB is also more and more popular recently non-relational database, here using SpringBoot+MongoDB to achieve a small case, of course, MongoDB actually do cache may not be much, but here just for a small demo simple learning use, For the purpose of getting started, more complex queries need to pay attention to the MongoDB official website.
If this post was helpful, please give it a thumbs up! Wechat search bigsai reply Bigsai get a collection of learning PDF!
Create the MongoDB database and project
Creating a MongoDB database
Mysql > create database (test); mysql > create database (news);
Create a project
First, open IDEA to create the project and select Create Springboot project:Then fill in both Gruop and AritifactcomandmongodemoJava Version Select Version 8.
When checking the module, check the Spring Web and MongoDB dependency modules here, select the appropriate location to create the project, and the project can be successfully created:
Preparatory work
After creating the project, we need to do some preparatory work to complete the cache. We will first add a configuration connection to the database in the application.properties section of the project as follows: Uri =mongodb:// Address: port/database name. In this case, the local mongodb database is used. The default port is 27017 and the name of the mongodb database is test.
spring.data.mongodb.uri=mongodb://localhost:27017/test
Copy the code
This allows you to connect to and access the local MongoDB test database in your project.
Next, create controller, service and POjo folders respectively in the com.mongodb directory of the project, and create newsController.java class in the Controller folder, which is responsible for the CONTROLLER url and logic:
package com.mongodemo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class newsController {
private static Logger logger= LoggerFactory.getLogger(newsController.class);
}
Copy the code
Among them:
- RestController declares the class as a controller and returns a JSON string to the front end.
- The Logger object is used to print logs. In web projects we prefer to print logs using logs rather than directly to the console.
Newsservice. Java = newsservice. Java = newsservice. Java = newsservice. Java = newsservice. Java = newsservice. Java = newsservice. Java
package com.mongodemo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
@Service
public class NewsService {
private static Logger logger= LoggerFactory.getLogger(NewsService.class);
@Autowired
MongoTemplate mongoTemplate;
}
Copy the code
Among them:
- @service indicates that this class is a Service (transaction) that can be injected into other objects (Spring manages it for you).
- @autoWired means to inject an object. MongoTemplate is an object that has been wrapped to manipulate MongoDB in Spring.
With the service created, we need to create the News class in the POJO to represent the news entity content.
import java.util.Date;
public class news {
private String title;
private Date date;
private String brief;
private String content;
private String author;
@Override
public String toString(a) {
return "news{" +
"title='" + title + '\' ' +
", date=" + date +
", brief='" + brief + '\' ' +
", content='" + content + '\' ' +
", author='" + author + '\' ' +
'} ';
}
public news(String title, Date date, String brief, String content, String author) {
this.title = title;
this.date = date;
this.brief = brief;
this.content = content;
this.author = author;
}
public String getTitle(a) {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDate(a) {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getBrief(a) {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getContent(a) {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor(a) {
return author;
}
public void setAuthor(String author) {
this.author = author; }}Copy the code
Each field is represented as:
The name of the | meaning |
---|---|
title | The title |
date | The date of |
brief | The profile |
content | content |
author | The author |
Cache the query
Before the implementation of cache, we should know the core role of cache: improve the query speed of web programs and put hot data into non-relational databases. This example is for caching the interface, but a real example of caching requires a lot of considerations such as timeliness, which data to cache and so on. The main purpose here is to illustrate an example of MongoDB.
There is usually a coordination between the cache and the database when querying:
In order to reduce the complexity of the whole project, manually generated data objects are used to replace the data queried in the database. We write the function getNewsByTitle(String title) in the NewsService, which returns the news data in the cache or database according to the title. Return the object directly if it exists in MongoDB, otherwise query it from the database (generated directly here), save it to MongoDB and return it. The specific code is:
public news getNewsByTitle(String title)
{
// Query data from MongoDB
Query query = new Query(Criteria.where("title").is(title));
news news=mongoTemplate.findOne(query, news.class);
if(news==null)// This record is not in the cache
{
logger.info("Query data from database");
// Suppose news1 is queried from the database
news news1=new news(title,new Date(),"".""."bigsai");
news1.setBrief("With Erudite Valley, mom no longer has to worry about my Java learning!");
news1.setContent("Erudite Valley quality learning materials provide a better environment for Java learning, more and more developers learn to use.");
mongoTemplate.insert(news1,"news");
logger.info("Data inserted into MongoDB successfully");
news=news1;
}
else {
logger.info("Data was successfully accessed from cache");
}
return news;
}
Copy the code
In the code above:
- Mongotemplate.findone (query, news.class), the first parameter is the query condition, the second parameter is the type of the query result into Java object, it helps you to automatically process.
- Query object is used to assist us to achieve conditional Query, which means that the Query condition is: the title field in MongoDB is the record of the title string passed in.
- Mongotemplate.insert (news1,”news”), the first parameter is the inserted document record, the second parameter is to connect to the corresponding MongoDB database under the Collections.
In newsController, we write an interface named getNews to return a JSON file of the headline (news class) to the user as follows:
@Autowired
NewsService newsService;
@GetMapping("getnews/{title}")
public news getnews(@PathVariable String title)
{
news news=newsService.getNewsByTitle(title);
return news;
}
Copy the code
In the code above:
- @autoWired (Required = false) is used to inject objects. The NewsService userService is used to inject objects. After injection, you don’t need to manually create objects.
- @getMapping (” getNews /{title}”) means to declare a get request interface,
We launch the program, browser inputLocalhost :8080/ getNews/Learn Java
The page returns a result that serializes a news object into a JSON string of text.
At the same time, you can check the log of IDEA, because there is no corresponding data in MongoDB for the first query, you can find that the database will be queried first and then stored in MongoDB:Check MongoDB’s news set and find that records are inserted successfully. Refresh the page several timesLocalhost :8080/ getNews/Learn Java
You’ll find that the data is returned directly from MongoDB:
Cache updates and deletes
Cache and storage of data in a relational database data is consistent, when we only query operation, can keep the consistency of the data, but if we have update, delete operations on the data, you need to update data in a relational database and directing at the same time, or delete operation, let the data again to achieve the effect of consistency.
The cache update
Although in most cases we rarely update hot news data, sometimes we need to change some content of news, such as score errors or inappropriate remarks.
We wrote the updateNewsContentByTitle((String title,String Content) function in NewsService to update the database (not implemented here) and MongoDB cache:
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 the content
update.set("date".new Date());// Update time
// Assume that the database is updated here
// updateFirst Updates the first result set returned by the query
// The upsert update is inserted if it does not exist
mongoTemplate.upsert(query, update, news.class);
}
catch (Exception e)
{
return false;
}
return true;
}
Copy the code
Among them:
- Query object to assist us in conditionally querying the data to be updated, which means that the Query condition is also as follows: the title field in MongoDB is the record of the title string passed in.
- The Update object is used to record updated fields and data. In this case, the content and date are updated.
- Mongotemplate. upsert(query, update, news.class) to implement the update, if the data does not exist in MongoDB then insert it into MongoDB.
Updatenews interface is used to update database data and cache MongoDB data:
@GetMapping("updatenews")
public String updatenews(String title,String content)
{
boolean bool=newsService.updateNewsContentByTitle(title,content);
if(bool)
return "Update successful";
else
return "Update failed";
}
Copy the code
Initiator accesslocalhost:8080/updatenews? Title = Learn Java&content = learn Java all over the world
, you will find that the data is updated successfully:
The cache to delete
In addition to data consistency during update, data consistency also needs to be ensured during deletion. If the data of relational database is deleted without deleting MongoDB cache, then the next query of this data exists in MongoDB but does not exist in relational database, resulting in data inconsistency. So when deleting data, we need to delete data in MongoDB.
DeleteNewsByTitle (String title) is used to delete MongoDB records by title in NewsService:
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;
}
Copy the code
mongoTemplate.remove(query,news.class); Indicates that the records that meet the query conditions are deleted from MongoDB. Query is the query condition, and news.class is the Java class for deleting the object.
Write the Deletenews interface in newsController to handle deletion requests:
@GetMapping("deletenews/{title}")
public String deletenews(@PathVariable String title)
{
try {
newsService.deleteNewsByTitle("Learn Java.");
return "Deleted successfully";
}
catch (Exception e)
{
return "Delete failed"; }}Copy the code
Start the program, accesshttp://localhost:8080/deletenews/ to learn Java
, the records cached in MongoDB are deleted successfully, which ensures that MongoDB does not have dirty data that does not exist in the relational database, achieving data consistency!
This is the end of this article, if you help, please do not be too generous to your small likes, collect a copy if there is more looking forward to sharing with you in the public account Bigsai.