springboot框架,中间库是mognodb,可以写入2个数据库的Demo

发布时间:2024年01月04日

1-springboot版本:
2.3.9.RELEASE
POM.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
<!--		<version>3.2.1</version>-->
		<version>2.3.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.jack</groupId>
	<artifactId>jackDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>jackDemo</name>
	<description>jackDemo</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.75</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

配置文件 application.properties:

server.port=8080
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=admin
spring.data.mongodb.username=root
spring.data.mongodb.password=XXXX
#spring.data.mongodb.host=XXX
spring.data.mongodb.host=XXX
spring.data.mongodb.replica-set-name=XXXX
spring.data.mongodb.port=3717
#spring.data.mongodb.uri=XXX


# ??????
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

# ?????????
logging.file.name=/data/logfile.log

# ??????
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n

MongoConfig代码:

package com.jack.XXX.util;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import java.util.Collections;

@Configuration
public class MongoConfig  {

    @Value("${spring.data.mongodb.authentication-database}")
    private String authDb;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private int port;

    @Bean
    public MongoClient mongoClient() {
        MongoCredential credential = MongoCredential.createCredential(username, authDb, password.toCharArray());

        return MongoClients.create(
                MongoClientSettings.builder()
                        .applyToClusterSettings(builder ->
                                builder.hosts(Collections.singletonList(new ServerAddress(host, port))))
                        .credential(credential)
                        .build()
        );
    }

    @Bean
    public MongoDatabaseFactory mongoDatabaseFactory(MongoClient mongoClient) {
        return new SimpleMongoClientDatabaseFactory(mongoClient, authDb);
    }

    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}

调用的时候,若使用默认库的就直接

    @Autowired
    private MongoTemplate mongoTemplate;
mongoTemplate.sve()调用就好。

若是使用别的数据库,则:

 MongoDatabaseFactory factoryForTestDb = new SimpleMongoClientDatabaseFactory(mongoClient, "test");//别的数据库名
        MongoTemplate mongoTemplateForTestDb = new MongoTemplate(factoryForTestDb);

        long timestamp = System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000;
        Criteria criteria = Criteria.where("timestamp").lt(timestamp);
        Query query = new Query(criteria);
        query.limit(300000); // Limit the number of documents returned

        List<DeleteCaches> documents = mongoTemplateForTestDb.find(query, DeleteCaches.class); // 使用新的mongoTemplateForTestDb来执行查询
        Iterator<DeleteCaches> iterator = documents.iterator();
        while(iterator.hasNext()) {
            DeleteCaches item = iterator.next();
            log.warn("待删除的_id:{}",item.getId());
            mongoTemplateForTestDb.remove(item);
        }
文章来源:https://blog.csdn.net/qq_41568648/article/details/135383782
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。