Spring Boot + docker +mongo

 

 

启动mongo镜像

docker run --name mongo-container -d -P mongo

连接到容器内

docker exec -it eb sh

输入:mongo

输入:show dbs

输入:db.stats()

 

 下载mongo客户端:https://robomongo.org/download

按ctrl+c 和 exit 退出容器,输入:docker ps 

这里自动映射的端口为32768,打开Robo 3T,输入地址,点击test

在左侧就能看到库了

 

新建spring-boot项目,添加pom引用

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.pegdown/pegdown -->
        <dependency>
            <groupId>org.pegdown</groupId>
            <artifactId>pegdown</artifactId>
            <version>1.6.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
View Code

定义User

package org.myshsky.mongodemo;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Document(collection = "user")
public class User {
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getRegistrationDate() {
        return registrationDate;
    }

    public void setRegistrationDate(Date registrationDate) {
        this.registrationDate = registrationDate;
    }

    public Set<String> getRoles() {
        return roles;
    }

    public void setRoles(Set<String> roles) {
        this.roles = roles;
    }

    @Id

    private String userId;
    @NotNull @Indexed(unique = true)
    private String username;
    @NotNull
    private String password;
    @NotNull
    private String name;
    @NotNull
    private String email;
    @NotNull
    private Date registrationDate=new Date();
    private Set<String> roles=new HashSet<>();
    @PersistenceConstructor
    public User(String userId, String username, String password, String name, String email, Date registrationDate, Set<String> roles) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.name = name;
        this.email = email;
        this.registrationDate = registrationDate;
        this.roles = roles;
    }

    public User() {

    }
}
View Code

查询接口UserRepository

package org.myshsky.mongodemo;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserRepository extends MongoRepository<User,String> {
    User findByUsername(String username);
}
View Code

配置类

package org.myshsky.mongodemo;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableMongoRepositories
@PropertySource("classpath:test.properties")
public class TestDataSourceConfig extends AbstractMongoConfiguration {
    @Autowired
    private Environment env;
    @Override
    protected String getDatabaseName() {
        return env.getRequiredProperty("mongo.name");
    }

    @Override
    public Mongo mongo() throws Exception {
        ServerAddress serverAddress = new ServerAddress(env.getRequiredProperty("mongo.host"));
        List<MongoCredential> credentials=new ArrayList<>();
        return new MongoClient(serverAddress,credentials);
    }
}
View Code

配置文件test.properties

#MongoDb
mongo.host=192.168.31.146:${mongo.port}
mongo.name=local
mongo.port=32768
View Code

单元测试

package org.myshsky.mongodemo;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoDemoApplicationTests {
    private static Logger logger= LoggerFactory.getLogger(MongoDemoApplicationTests.class);
    @Autowired
    UserRepository userRepository;
    @Before
    public void setup(){
        Set<String> roles=new HashSet<>();
        roles.add("manage");
        User user=new User("1","user","12345678","name","email@com.cn",new Date(),roles);
        userRepository.save(user);
    }
    
    @Test
    public void findAll(){
        List<User> users=userRepository.findAll();
        Assert.notNull(users);
        for(User user:users){
            logger.info("===user=== userid:{},username:{},pass:{},registrationDate:{}",
                    user.getUserId(),user.getName(),user.getPassword(),user.getRegistrationDate());
        }
    }
}
View Code

运行测试

 

通过客户端查看

 

posted @ 2018-01-03 22:36  uptothesky  阅读(552)  评论(0编辑  收藏  举报