SpringBoot integrates MongoDB (implement a simple cache)

Preface

SpringBoot is a commonly used development framework, and MongoDB is also a non-relational database that has become more and more popular recently. Here is a small case using SpringBoot+MongoDB. Of course, MongoDB may not actually do caching, but here is just a simple study for a small demo For the purpose of using, getting started, more complex queries need to pay attention to the MongoDB official website.

If this article is helpful to you, please like and support it! WeChat search and bigsaireply bigsai to get a copy of the collection of learning pdf!

If you don't know much about MongoDB, please read the previous article on MongoDB from the site to the Buddha .

Create MongoDB database and project

Create MongoDB database

Open the Studio 3T database management tool, connect to the local MongoDB database, create a database named test, and create a collection named news in the test database:

Insert picture description here

Create project

First, open IDEA to create a project, choose to create a Springboot project:
Insert picture description here
Then when you select Gruop and Aritifact, fill in com and mongodemo respectively, and select version 8 for Java Version.
Insert picture description here

When checking the module, check the Spring web and MongoDB dependency modules here, choose a suitable location to create the project, and the project can be successfully created:

Insert picture description here

Preparatory work

After creating the project, we need to do some preparatory work to complete the cache. We first need to add configuration to the application.properties in the project to connect to the database, the configuration rules are:, spring.data.mongodb.uri=mongodb://地址:端口/数据库名this case uses the local MongoDB database, the default port is 27017, and the specific MongoDB database name used is test, then you can follow the following To configure:

spring.data.mongodb.uri=mongodb://localhost:27017/test

In this way, you can connect to and access the local MongoDB test database in the project.

Secondly, create the controller, service, and pojo folders in the com.mongodb directory of the project, and create a newsController.javaclass under the controller folder, which is the controller responsible for the 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);
    
    
}

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 use log to print logs rather than directly output in the console.

After the controller is created, create a NewsService.javaclass under the service folder , and write the following content first:

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;
    
}

among them:

  • @Service means that this class is a service (transaction processing), which can be injected into other objects (Spring manages it for you).
  • @Autowired means to inject an object. The MongoTemplate is an object that has been encapsulated to operate MongoDB in Spring.

After the service is created, we need to create a news class in pojo to represent the content of news entities.

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() {
    
    
        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() {
    
    
        return title;
    }
    public void setTitle(String title) {
    
    
        this.title = title;
    }
    public Date getDate() {
    
    
        return date;
    }
    public void setDate(Date date) {
    
    
        this.date = date;
    }
    public String getBrief() {
    
    
        return brief;
    }
    public void setBrief(String brief) {
    
    
        this.brief = brief;
    }
    public String getContent() {
    
    
        return content;
    }
    public void setContent(String content) {
    
    
        this.content = content;
    }
    public String getAuthor() {
    
    
        return author;
    }
    public void setAuthor(String author) {
    
    
        this.author = author;
    }
}

The fields are represented as:

name meaning
title title
date date
brief Overview
content content
author Author

Cache query

Let's start the actual battle of MongoDB to implement a news cache function. Before implementing the cache, we must understand the core role of the cache: improve the query speed of web programs and put hot data in a non-relational database. In this case, the interface is cached, but the real cache instance needs to consider many issues such as timeliness and caching of those data. Here is mainly to explain an example of MongoDB.

When querying, the cache and the database usually cooperate like this:

Insert picture description here

In order to reduce the complexity of the entire project, here we use manually generated data objects to replace the data queried in the database. We write the getNewsByTitle(String title) function in NewsService. Its function is to return the news data in the cache or database according to the title. If it exists in MongoDB, the object will be returned directly, otherwise it will be queried from the database (generated directly here), then stored in MongoDB and returned. The specific code is:

public news getNewsByTitle(String title)
   {
    
    
       //查询数据先从MongoDB中查询
       Query query = new Query(Criteria.where("title").is(title));
       news news=mongoTemplate.findOne(query, news.class);
       if(news==null)//缓存中没该条记录
       {
    
    
           logger.info("从数据库查询数据");
           //假设news1从数据库中查询
           news news1=new news(title,new Date(),"","","bigsai");
           news1.setBrief("有了博学谷,妈妈再也不用担心我的java学习!");
           news1.setContent("博学谷优质学习资料为java学习提供更好环境,越来越多开发者学习使用");
           mongoTemplate.insert(news1,"news");
           logger.info("数据插入到MongoDB成功");
           news=news1;
       }
       else {
    
    
           logger.info("数据从缓存访问成功");
       }
       return  news;
   }

In the above code:

  • Our core use mongoTemplate object to query a record, the query statement is: mongoTemplate.findOne(query, news.class), the first parameter is the query condition, and the second parameter is the type of the query result converted into a Java object. Help you handle it automatically.
  • Use the Query object to assist us in implementing the conditional query, which means that the query condition is: the title field in MongoDB is the record of the incoming title string.
  • The syntax for inserting is mongoTemplate.insert(news1, "news"), the first parameter is the document record to be inserted, and the second parameter is the collection (Collections) under the database corresponding to MongoDB.

In newsController, we write an interface named getnews, which is used to return a JSON file of the headline news (news class) to the user. The specific code is:

  @Autowired
   NewsService newsService;

   @GetMapping("getnews/{title}")
   public news getnews(@PathVariable String title)
   {
    
    
        news news=newsService.getNewsByTitle(title);
       return  news;
   }

In the above code:

  • @Autowired(required = false) is used to inject objects. The following NewsService userService is the injected object. After injection, you don’t need to manually create the object and you can use it directly (Spring will manage it for you)
  • @GetMapping(“getnews/{title}”) means an interface that declares a get request method,

When we start the program, the browser input localhost:8080/getnews/好好学javapage will return the result, and the returned news object will be serialized into a JSON string text.
Insert picture description here

At the same time, you check IDEA's log. Because there is no corresponding data in MongoDB for the first query, you will find that you will first query from the database and then store it in MongoDB:
Insert picture description here
check the news collection of MongoDB and find that the record is successfully inserted, refresh the page for localhost:8080/getnews/好好学javayou You will find that the data will be returned directly from MongoDB:
Insert picture description here

Cache update, delete

The data in the cache is consistent with the data of the stored relational database. When we only have query operations, we can always maintain the consistency of the data. However, if we update or delete the data, we need to perform the relational database and MongoDB The data in the data is updated or deleted at the same time, so that the data can achieve consistency again.

Cache update

Although in most cases we may rarely update the hot news data, but sometimes there are parts of the news that need to be changed, such as score typos or inappropriate remarks.

We write the updateNewsContentByTitle((String title, String content) function in NewsService, which is used to update the data in the database (not implemented here) and the 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.set("date",new Date());//更新时间
            // 假设在这里数据库中更新过这里跳过
            
            // updateFirst 更新查询返回结果集的第一条
            //upsert 更新如果不存在就插入
            mongoTemplate.upsert(query, update, news.class);
        }
        catch (Exception e)
        {
    
    
            return  false;
        }
        return  true;
    }

among them:

  • The Query object assists us in realizing the conditional query of the data to be updated. The meaning here is that the query condition is also: the title field in MongoDB is the record of the incoming title string.
  • The Update object is used to record updated fields and data. Here, the content and date passed in are updated.
  • mongoTemplate.upsert(query, update, news.class) is used to implement the update. If the data does not exist in MongoDB, it will be inserted into MongoDB.

After writing the service, write an interface named updatenews in newsController to update database data and data cached in MongoDB:

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

Start the program to visit localhost:8080/updatenews?title=好好学java&content=学好java走遍全天下, you will find that the data update is successful:
Insert picture description here

Cache delete

In addition to ensuring data consistency when updating, and data consistency when deleting, if you delete the data of the relational database without deleting the MongoDB cache, then the next time you query the data that exists in MongoDB but does not exist in the relational database, This causes data inconsistencies, so when deleting data, we need to delete the data in MongoDB.

Write the deleteNewsByTitle(String title) function in NewsService to delete records in MongoDB according to the title:

 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); means to delete records that meet the query conditions from MongoDB. Among them, query is the query condition, and news.class is the class of the deleted object in Java.

Write the deletenews interface in newsController to handle delete requests:

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

Start the program and visit http://localhost:8080/deletenews/好好学java, and you will find that the records cached in MongoDB have been successfully deleted. This ensures that there will be no dirty data that does not exist in the relational database in MongoDB, and data consistency is achieved!
Insert picture description here

This is the end of this article. If you help, please don't be stingy with your small likes. If you have more expectations, please pay attention to the public bigsaiaccount and reply to bigsai to get a copy of the collection of pdf resources!

Guess you like

Origin blog.csdn.net/qq_40693171/article/details/108157431