spring boot mongodb config

原创
2018/04/09 11:37
阅读数 1K
@Configuration
class SpringMongoConfig {
    @Value("\${spring.data.mongodb.host}")
    private val host: String? = null
    @Value("\${spring.data.mongodb.port}")
    private val port: Int? = 27017
    @Value("\${spring.data.mongodb.database}")
    private val database: String? = "database"

    @Bean
    fun mongoTemplate(): MongoTemplate {
        val options = MongoClientOptions.Builder().socketKeepAlive(true).build()
        val factory = SimpleMongoDbFactory(MongoClient(ServerAddress(host!!, port!!), options), database)
        //remove _class
        val converter = MappingMongoConverter(factory, MongoMappingContext())
        converter.typeMapper = DefaultMongoTypeMapper(null)
        return MongoTemplate(factory, converter)
    }
}

application.yml:

---
spring:
  profiles: dev
  data:
    mongodb:
      host: localhost
      port: 27017
      database: database

多个数据库:

@Configuration
class MongoConfig {
    @Value("\${spring.data.mongodb.host}")
    private val host: String? = null
    @Value("\${spring.data.mongodb.port}")
    private val port: Int? = 27017
    @Value("\${spring.data.mongodb.database}")
    private val maker = "maker"

    @Value("\${spring.data.mongodb1.host}")
    private val host1: String? = null
    @Value("\${spring.data.mongodb1.port}")
    private val port1: Int? = 27017
    @Value("\${spring.data.mongodb1.database}")
    private val maker2 = "maker"

    @Bean
    fun makerTemplate(): MongoTemplate {
        val factory = SimpleMongoDbFactory(MongoClient(host!!, port!!), maker)
        //remove _class
        val converter = MappingMongoConverter(factory, MongoMappingContext())
        converter.setTypeMapper(DefaultMongoTypeMapper(null))
        return MongoTemplate(factory, converter)
    }

    @Bean
    @Primary
    fun maker2Template(): MongoTemplate {
        val factory = SimpleMongoDbFactory(MongoClient(host1!!, port1!!), maker2)
        //remove _class
        val converter = MappingMongoConverter(factory, MongoMappingContext())
        converter.setTypeMapper(DefaultMongoTypeMapper(null))
        return MongoTemplate(factory, converter)
    }
}

配置文件:

---
spring:
  profiles: product
  data:
    mongodb:
      host: mongo
      port: 27017
      database: maker
    mongodb1:
      host: mongo
      port: 27017
      database: maker2

用法:

@RestController
@RequestMapping("/")
class ReportController {
    @Autowired
    @Qualifier("makerTemplate")
    private lateinit var makerTemplate: MongoTemplate
    @Autowired
    @Qualifier("maker2Template")
    private lateinit var maker2Template: MongoTemplate
    ...
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部