1. 程式人生 > >Spring Boot + docker +mongo

Spring Boot + docker +mongo

down local cor username hash factor his ron imp

啟動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 protected]",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

運行測試

技術分享圖片

通過客戶端查看

技術分享圖片

Spring Boot + docker +mongo