Method of using mongodb connection pool configuration in spring boot

Because today's development encountered performance problems, which may be related to the connection of mongodb, I took a little in-depth look and found that someone had written this related content, so I reprinted it. You can write an extension to spring forall when you have time. The main idea is the same. Thanks for this beautiful Cheng Xuyuan's article!

explain

Spring boot relies on spring boot starter data mongodb to realize the automatic configuration of spring data mongodb.

However, by default, spring boot does not provide the function of connection pool configuration like MySQL or redis. Therefore, we need to rewrite mongodbfactory to realize the parameter configuration extension of mongodb client connection.

It should be noted that the mongodb client itself is a connection pool, so we only need to configure the client.

configuration file

In order to unify the configuration of spring boot, we need to configure the rewritten configuration to application In YML, the prefix is spring data. mongodb. Under custom (prefix can be configured freely):

In this configuration example, the replica set is configured, which contains host 10.0 5.1: 27017 and 10.0 5.1:27018. Other configurations are similar to the standard configuration of spring boot. In addition, connections per host is the number of connections of the client, and in connections per host is the minimum number of connections of the client.

Wrap configurations into classes

To facilitate calling and readability, wrap the above configuration into a configuration entity class, mongoconfig The Java code is as follows:

Overwrite mongodbfactory

Next, overwrite the original mongodbfactory bean of spring boot and create a new file mongoconfig Java, the code is as follows:

Here, you can set the previously configured parameters during mongodb connection. According to your actual situation, you can add and modify the required configuration parameters during new simplemongodbfactory.

At this point, you have completed all the configuration and run the test.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>