什么是Docker
Docker最近在业内非常火。如果你现在还不知道Docker是什么,你可要小心喽。今后,你会发现自己正在以某种方式使用它。本文假设你已经有了Docker的基础。如果你现在对它还不是很熟悉,我确定你以后还会来读这篇文章。
Docker用于集成测试、复杂分布式系统演示,非常理想。甚至可以用于运行生产环境下的系统。它是一个开源的软件容器。你可以把它想像成一个非常轻的超级快的虚拟机。
例子
得到“Integration testing with Maven and Docker”文章和Docker Java API项目的启发,我写了一个简单的可以管理Docker容器maven插件,Docker Maven Plugin。这个插件将会根据你的配置,在构建时启动容器,构建结束时停止容器并删除,如果本地找不到镜像,Docker会自动去中央仓库下载。
以下与Apache Camel的集成测试是被忽略的,因为测试需要一个Redis实例才可以执行:
package org.apache.camel.component.redis;
importorg.apache.camel.impl.JndiRegistry;
importorg.junit.Ignore;
importorg.junit.Test;
importorg.springframework.data.redis.connection.jedis.JedisConnectionFactory;
importorg.springframework.data.redis.core.RedisTemplate;
@Ignore
public classRedisProducerIntegrationTest extends RedisTestSupport {
private static final JedisConnectionFactory CONNECTION_FACTORY = new JedisConnectionFactory();
static {
CONNECTION_FACTORY.afterPropertiesSet();
}
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry registry = super.createRegistry();
redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(CONNECTION_FACTORY);
redisTemplate.afterPropertiesSet();
registry.bind("redisTemplate", redisTemplate);
returnregistry;
}
@Test
public void shouldSetAString() throws Exception {
sendHeaders(
RedisConstants.COMMAND, "SET",
RedisConstants.KEY, "key1",
RedisConstants.VALUE, "value");
assertEquals("value", redisTemplate.opsForValue().get("key1"));
}
@Test
public void shouldGetAString() throws Exception {
redisTemplate.opsForValue().set("key2","value");
Object result = sendHeaders(RedisConstants.KEY, "key2", RedisConstants.COMMAND,"GET");
assertEquals("value", result);
}
}
我们配置docker-maven-plugin使用一个Redis镜像同时让主机的6379端口映射到容器的6379端口:
com.ofbizian
docker-maven-plugin
1.0.0
dockerfile/redis
{
"PortBindings": {
"6379/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "6379"
}
]
}
}
]]>
start-docker
pre-integration-test
start
stop-docker
post-integration-test
stop
插件在编译期启动一个Docker容器,然后在集成测试结束期关闭容器。
这是一个非常简单的例子,但是这个插件支持更多的场景,如多镜像不同配置;将启动/关闭容器动作定义在不同的maven构建期间。Enjoy.
【编辑推荐】
【责任编辑:林师授 TEL:(010)68476606】