Java Mongo怎么写

Java + Mongo 集群

使用 SpringData Mongo操作mongo数据库
依赖的包叫做

spring-data-mongodb

groupId是 org.springframework.data

先前积累了一套 mongo的做法,但是只能针对于单点进行操作,这个教程可以帮助你,无论是单点还是集群,都能连接的上进行操作

配置文件 application.yml:

spring:
    mongodb:
        address:
            - "10.204.0.100:31017"
        database: cmseditor
        replicaSet: ""
        maxSize: 10
        minSize: 4
        maxWaitTime: 20000   
        maxConnectionLifeTime: 300000
        maxConnectionIdleTime: 100000

这里因为是 单点的mongo,所以 replicaSet写成 “”,待会儿会对replicaSet的值进行判断,来判断它是单点还是集群

配置类:

@Configuration
@ConfigurationProperties(prefix = "spring.mongodb")
@Slf4j
@Setter
@Getter
@ToString
public class MongoClientConfiguration extends AbstractMongoClientConfiguration {

    private List<String> address;
    private String replicaSet;
    private String database;
    private Integer maxSize;
    private Integer minSize;
    private Long maxWaitTime;
    private Long maxConnectionLifeTime;
    private Long maxConnectionIdleTime;

    @Override
    protected @NotNull String getDatabaseName() {
        return database;
    }

    @Override
    @RefreshScope
    @Bean
    public @NotNull MongoClient mongoClient() {
        // MongoDB地址列表
        List<ServerAddress> serverAddresses = new ArrayList<>();
        log.info("serverAddresses={}",serverAddresses);
        log.info("replicaSet={}",replicaSet);
        log.info("maxWaitTime={}",maxWaitTime);

        log.info("replicaSet={}",replicaSet);
        for (String addr : address) {
            String[] hostAndPort = addr.split(":");
            ServerAddress serverAddress = new ServerAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
            serverAddresses.add(serverAddress);
        }

        log.info("serverAddresses:" + serverAddresses.toString());

        // 创建MongoDbFactory
        ConnectionPoolSettings poolSettings = ConnectionPoolSettings.builder().maxSize(maxSize).minSize(minSize)
                .maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS)
                .maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS)
                .maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.MILLISECONDS)
                .build();
        MongoClientSettings settings = MongoClientSettings.builder().applyToConnectionPoolSettings(builder -> builder.applySettings(poolSettings))
                .applyToClusterSettings(builder -> {
                            builder.hosts(serverAddresses);
                            if (StrUtil.isNotEmpty(replicaSet)) {
                                builder.requiredReplicaSetName(replicaSet);
                            }
                        }
                ).build();
        return MongoClients.create(settings);
    }

}

注意这里有一个 if (StrUtil.isNotEmpty(replicaSet)) ,就是通过这层设置来判断是集群连接还是单点连接。、

然后写Mongo工具类:

import com.mongodb.client.MongoClient;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;


@Component
public class NewsDetailMongoTemplateUtils {

    @Autowired
    MongoClient mongoClient;

    @NotNull
    private String getBeanName(@NotNull String database) {
        return "mongoTemplate" + database;
    }

    @Autowired
    ApplicationContext applicationContext;


    public MongoTemplate getMongoTemplate(@NotNull String database) {
        String beanName = getBeanName(database);


        if (!applicationContext.containsBeanDefinition(beanName)) {
            synchronized (this) {
                if (!applicationContext.containsBeanDefinition(beanName)) {
                    System.out.println("create bean");
                    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(MongoTemplate.class, () -> new MongoTemplate(mongoClient, database));
                    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
                    beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
                }
            }
        }
        Object bean = applicationContext.getBean(beanName);
        return (MongoTemplate) bean;
    }

}

之后在文件中,它是这样调用的

MongoOperations mongoOps = newsDetailMongoTemplateUtils.getMongoTemplate("cmseditor");
Query queryToday = new Query(Criteria.where("userid").is(userId));
String snsToday= mongoOps.findOne(queryToday, String.class, "tshPersonKpi");
SnsPersonalBean one = mongoOps.findOne(queryToday, SnsPersonalBean.class);
log.info("{}", one);

cmseditor是数据库名称,tshPersonKpi是collection名称。哦对了,还有Mongo的实体类是怎么定义的。

其实就是在原本的类的声明的基础上加了 @Document的注解

@Doucument(collection = "tshPersonKpi")
@Data
public User{

	private Integer id;
	
	private String name;
	
	private Verify verify;
	
	@Data
	@Document
	public Verify{
	
		Integer article;
		
		Integer shortView;
	
	}
}


然后有机会总结一下 mongo的聚合查询在Java当中怎么使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值