|
| 1 | +/* |
| 2 | + * Copyright 2016 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package example.springdata.redis.test.util; |
| 17 | + |
| 18 | +import java.io.IOException; |
| 19 | + |
| 20 | +import org.junit.rules.ExternalResource; |
| 21 | + |
| 22 | +import redis.embedded.RedisServer; |
| 23 | + |
| 24 | +/** |
| 25 | + * JUnit rule implementation to start and shut down an embedded Redis instance. |
| 26 | + * |
| 27 | + * @author Christoph Strobl |
| 28 | + * @author Oliver Gierke |
| 29 | + */ |
| 30 | +public class EmbeddedRedisServer extends ExternalResource { |
| 31 | + |
| 32 | + private static final int DEFAULT_PORT = 6379; |
| 33 | + private RedisServer server; |
| 34 | + private int port = DEFAULT_PORT; |
| 35 | + private boolean suppressExceptions = false; |
| 36 | + |
| 37 | + public EmbeddedRedisServer() { |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + protected EmbeddedRedisServer(int port) { |
| 42 | + this.port = port; |
| 43 | + } |
| 44 | + |
| 45 | + public static EmbeddedRedisServer runningAt(Integer port) { |
| 46 | + return new EmbeddedRedisServer(port != null ? port : DEFAULT_PORT); |
| 47 | + } |
| 48 | + |
| 49 | + public EmbeddedRedisServer suppressExceptions() { |
| 50 | + this.suppressExceptions = true; |
| 51 | + return this; |
| 52 | + } |
| 53 | + |
| 54 | + /* |
| 55 | + * (non-Javadoc) |
| 56 | + * @see org.junit.rules.ExternalResource#before() |
| 57 | + */ |
| 58 | + @Override |
| 59 | + protected void before() throws IOException { |
| 60 | + |
| 61 | + try { |
| 62 | + |
| 63 | + this.server = new RedisServer(this.port); |
| 64 | + this.server.start(); |
| 65 | + } catch (Exception e) { |
| 66 | + if (!suppressExceptions) { |
| 67 | + throw e; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + /* |
| 73 | + * (non-Javadoc) |
| 74 | + * @see org.junit.rules.ExternalResource#after() |
| 75 | + */ |
| 76 | + @Override |
| 77 | + protected void after() { |
| 78 | + |
| 79 | + try { |
| 80 | + this.server.stop(); |
| 81 | + } catch (Exception e) { |
| 82 | + if (!suppressExceptions) { |
| 83 | + throw e; |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments