MongoDB系列之-微服务集成

一.微服务地址

因为之前作者已经转备好了开发环境,客户端工具也能正常连接,我部署在Linux百度云服务器的MongoDB服务,所以我本地新建微服务模块,用两种方式建立与MongoDB服务的连接。下面是我创建的微服务gitee地址,里面有代码。
MongoDB与微服务集成代码部分,请点击!!!

在这里插入图片描述我这里只同步了与MongoDB服务连接的交互,不涉及具体的操作。

二.必须依赖的JAR包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-context</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

三.两种连接方式

  1. 代码连接
    public void mongodbNoAutowired()
    {
        try {
            // 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
            // ServerAddress()两个参数分别为 服务器地址 和 端口
            ServerAddress serverAddress = new ServerAddress("106.12.175.83",27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);

            // MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential("test", "test", "mongodb".toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);

            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs, credentials);

            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
            log.info("MongodbJdbcService|mongodbNoAutowired|Connect to database successfully");
            log.info("MongodbJdbcService|mongodbNoAutowired|连接到数据库:={}", mongoDatabase.getCollection("test"));
        } catch (Exception e) {
            log.error( "MongodbJdbcService|mongodbNoAutowired|数据库连接测试异常:={}", e.getClass().getName() + ": " + e.getMessage() );
        }
    }
  1. 注解映射
    配置文件:
spring:
 data:
   mongodb:
     uri: mongodb://test:[email protected]:27017/test

添加注解即可:

	private final MongoTemplate mongoClient;

    @Autowired
    public MongodbJdbcService(MongoTemplate mongoClient)
    {
        this.mongoClient = mongoClient;
    }

	public void mongodbAutowired()
    {
        MongoCollection<Document> people = this.mongoClient.getCollection("people");
        log.info("MongodbJdbcService|mongodbAutowired|集合大小:={}", people.count());
        if (Objects.isNull(people))
        {
            people = this.mongoClient.createCollection("people");
        }
        log.info("MongodbJdbcService|mongodbAutowired|使用注解连接MongoDB|创建集合请求出参:={}", people);
    }

这上面的两种方式都可以成功连接上MongoDB服务,需要注意的是:
spring-boot-starter-web:包自动帮我们引入了web模块开发需要的相关jar包。
spring-cloud-context:主要是构建了一个Bootstrap容器,并让其成为原有的springboot程序构建的容器的父容器。

四.拓展

大家,有兴趣可以自己研究一下,Spring 自动装配机制。

SpringBoot深入(一)自动装配机制初探
SpringBoot自动装配原理

发布了215 篇原创文章 · 获赞 135 · 访问量 114万+

猜你喜欢

转载自blog.csdn.net/weinichendian/article/details/103920236