Spring boot+mongodb+doc instance

  docker, mongodb, springboot

mongodb docker

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

robomongo(mongo mac client)

clipboard.png

View data

clipboard.png

springboot

  • Pom dependency
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
  • 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<Visitor,String> {
}
  • 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);
    }
  • Access

http://192.168.99.100:9001/product/visit

References