原文:https://blog.csdn.net/qq_35418518/article/details/107411512?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
yml :
pring: data: mongodb: primary: uri: mongodb://name:passward123@192.168.34.160:27017/test_1?slaveOk=true secondary: uri: mongodb://name:passward123@192.168.34.160:27017/test_2?slaveOk=true
推荐使用uri ,这样方便添加可选配置
mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/test?replicaSet=myRepl&authSource=admin
如果出现,uri中使用特殊字符。使用16进制进行URL编码代替。(@被使用,%40替换。:被使用,%3A替换)
eg:
读取偏好选项
读取首选项描述了与副本集有关的读取操作的行为。 这些参数允许你在连接字符串中基于每个连接指定读取首选项。
- readPreference
- maxStalenessSeconds
- readPreferenceTags
-
连接池选项
- maxPoolSize
- minPoolSize
- maxIdleTimeMS
- waitQueueMultiple
- waitQueueTimeoutMS
-
连接选项
- ssl
- connectTimeoutMS
- socketTimeoutMS
- compressors
- zlibCompressionLevel
.目录结构: (不同数据源的使用不同的目录,entity 和repository 置于目录下!!!)
4. game实体类
@Document(collection = "info_account") @Accessors(chain = true) @Data public class AccountInfo { @Id private String account; private int gameId; private String passWord; }
game repository
public interface AccountRepository extends MongoRepository<AccountInfo,String> { List<AccountInfo> findAllByAccount(String account); }
game 数据源配置(每个数据源单独一个配置文件)
@Configuration @EnableMongoRepositories(basePackages = "com.gray.database.game", mongoTemplateRef = "gameDBTemplate") public class GameDBConfig { @Bean @Primary @ConfigurationProperties(prefix="spring.data.mongodb.primary") public MongoProperties primaryMongoProperties() { return new MongoProperties(); } @Primary @Bean(name = "gameDBTemplate") public MongoTemplate primaryMongoTemplate() throws Exception { return new MongoTemplate(primaryFactory(primaryMongoProperties())); } @Bean @Primary public MongoDbFactory primaryFactory(MongoProperties mongoProperties) throws Exception { ConnectionString connectionString = new ConnectionString(mongoProperties.getUri()); return new SimpleMongoClientDbFactory(connectionString); } }