springboot+mongodb+docker实例

mongodb docker

mongodb:
  image: daocloud.io/library/mongo:latest
  ports:
    - "27017:27017"

robomongo(mongo mac client)

查看数据

springboot

  • pom依赖
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
  • application.yml
spring:
  data:
    mongodb:
      host: mongodb
      port: 27017
      database: docker-demo-java-mongo
      repositories:
        enabled: true
  • domain
import org.springframework.data.annotation.Id;

import java.util.Date;

/**
 * Created by codecraft on 2016-05-20.
 */
public class Visitor {

    @Id
    String id;
    String ip;
    Date visitDate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Date getVisitDate() {
        return visitDate;
    }

    public void setVisitDate(Date visitDate) {
        this.visitDate = visitDate;
    }
}
  • dao
public interface VisitorRepository extends MongoRepository {
}
  • controller
@Autowired
    VisitorRepository visitorRepository;

    @RequestMapping(value = "/product/visit",method = RequestMethod.GET)
    public String visit(HttpServletRequest request){
        Visitor visitor = new Visitor();
        visitor.setId(UUID.randomUUID().toString());
        visitor.setIp(request.getRemoteAddr());
        visitor.setVisitDate(new Date());
        visitorRepository.save(visitor);
        Long count =  visitorRepository.count();
        return String.format("你是来自%s的第%d位访问者。",request.getRemoteAddr(),count);
    }
  • 访问

http://192.168.99.100:9001/product/visit

参考

  • Docker 环境下的 Spring Boot 和 MongoDB 集成(不错)
  • spring-boot-sample-data-mongodb
  • Robomongo
  • MongoHub

你可能感兴趣的:(springboot,mongodb,docker)