spring boot mongodb config

@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
    ...
}

转载于:https://my.oschina.net/wower/blog/1791646

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值