2

mongodb docker

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

robomongo(mongo mac client)

clipboard.png

查看数据

clipboard.png

springboot

  • pom依赖
        <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);
    }
  • 访问

http://192.168.99.100:9001/product/visit

参考


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...