Skip to content

Commit 169ebf2

Browse files
committed
some cleanup
1 parent e80fb23 commit 169ebf2

File tree

4 files changed

+62
-55
lines changed

4 files changed

+62
-55
lines changed

README.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ System.out.println((String)l.get(0)); // prints "A"
3232
```
3333

3434
You will have to do some casting yourself in case of List responses. The
35-
reasoning here is that you know what data to expect so you're responsible for
35+
reasoning here is that you know what data to expect, so you're responsible for
3636
applying the correct casts in the correct context.
3737

3838
Refer to the Redis documentation for the return types of all calls and
@@ -61,7 +61,7 @@ redis.pipeline()
6161
This will result in a `List<Object>` containing a list for each of the responses.
6262

6363
## Is the connection thread safe?
64-
No. You need to make sure that the connection is accessed atomically. However,
64+
No. You need to make sure to access the connection atomically. However,
6565
there is a `Redis.run()` method which you can use to do some simple redis
6666
operations in isolation. It creates a connection and closes it directly after:
6767

@@ -73,11 +73,11 @@ nl.melp.redis.Redis.run((redis) -> redis.call("INCR", "mycounter"));
7373
However you wish. This library is a protocol implementation only. Managing a
7474
connection pool is not at all Redis-specific, so it doesn't belong here.
7575

76-
Having said that, this mostly depends on your use case. Typically if you have a
76+
Having said that, this mostly depends on your use case. Typically, if you have a
7777
webserver with 20 threads, you can have a socket per thread managed somewhere
78-
(e.g. ThreadLocal) and if you run a threadpool with 20 workers you can have one
78+
(e.g. ThreadLocal) and if you run a thread pool with 20 workers you can have one
7979
socket per thread there as well. This keeps things simple and practical to
80-
reason about and you don't have to worry who needs to create the socket at what
80+
reason about, and you don't have to worry who needs to create the socket at what
8181
point in time. You do need some error handling which, in case of managing the
8282
sockets centrally is a tiny bit easier. On the other hand, if you expect to be
8383
creating a lot of threads and not a lot of these threads need the connection,

src/nl/melp/redis/protocol/Encoder.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@ public class Encoder {
1111
/**
1212
* CRLF is used a lot.
1313
*/
14-
private static byte[] CRLF = new byte[]{'\r', '\n'};
14+
private static final byte[] CRLF = new byte[]{'\r', '\n'};
1515

1616
/**
1717
* This stream we will write to.
1818
*/
1919
private final OutputStream out;
2020

2121
/**
22-
* Construct the encoder with the passed outputstream the encoder will write to.
22+
* Construct the encoder with the passed output stream the encoder will write to.
2323
*
2424
* @param out Will be used to write all encoded data to.
2525
*/

src/nl/melp/redis/protocol/Parser.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package nl.melp.redis.protocol;
22

3-
import nl.melp.redis.Redis;
4-
53
import java.io.IOException;
64
import java.io.InputStream;
75
import java.util.Arrays;
@@ -96,7 +94,7 @@ public Object parse() throws IOException, ProtocolException {
9694
* @return The parsed response
9795
* @throws IOException Propagated from underlying stream.
9896
*/
99-
private byte[] parseBulkString() throws IOException, ProtocolException {
97+
private byte[] parseBulkString() throws IOException {
10098
final long expectedLength = parseNumber();
10199
if (expectedLength == -1) {
102100
return null;
@@ -127,14 +125,26 @@ private byte[] parseBulkString() throws IOException, ProtocolException {
127125
* @throws IOException Propagated from underlying stream.
128126
*/
129127
private byte[] parseSimpleString() throws IOException {
130-
return scanCr(1024);
128+
return scanCr();
131129
}
132130

131+
/**
132+
* Parse a number (as long)
133+
* @return The number
134+
* @throws IOException Propagated from underlying stream
135+
*/
133136
private long parseNumber() throws IOException {
134-
return Long.valueOf(new String(scanCr(1024)));
137+
return Long.parseLong(new String(scanCr()));
135138
}
136139

137-
private byte[] scanCr(int size) throws IOException {
140+
/**
141+
* Scan the input stream for the next CR character
142+
*
143+
* @return Byte array.
144+
* @throws IOException Propagated from underlying stream
145+
*/
146+
private byte[] scanCr() throws IOException {
147+
int size = 1024;
138148
int idx = 0;
139149
int ch;
140150
byte[] buffer = new byte[size];

test/nl/melp/redis/RedisTest.java

Lines changed: 39 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,24 @@
2626
import java.util.function.Supplier;
2727

2828
public class RedisTest {
29+
private static final String REDIS_HOST = System.getProperty("redis.host", "localhost");
30+
private static final int REDIS_PORT = Integer.parseInt(System.getProperty("redis.port", "6379"));
31+
private static final int numThreads = Integer.parseInt(System.getProperty("redis.test.num-threads", "200"));
32+
private static final int numMessages = Integer.parseInt(System.getProperty("redis.test.num-messages", "25000"));
33+
34+
// 16 bits buffer size (2 ^ 16, 1<<16) seems to be the most efficient for any value size.
35+
// tweak these numbers to check if this is the case for you.
36+
private static final int numBitsFrom = Integer.parseInt(System.getProperty("redis.test.num-bits-from", "16"));
37+
private static final int numBitsTo = Integer.parseInt(System.getProperty("redis.test.num-bits-to", "16"));
38+
2939
public static void main(String[] args) throws IOException, InterruptedException {
3040
if (args.length == 0) {
3141
testParse();
42+
binaryTest();
3243
managedTest();
3344
integrationTest();
34-
// 16 bits buffer size (2 ^ 16, 1<<16) seems to be the most efficient for any value size.
35-
// tweak these numbers to check if this is the case for you.
36-
bufferSizePerformanceTest(16, 16);
45+
bufferSizePerformanceTest();
3746
socketManagementPerformanceTest();
38-
binaryTest();
3947
subscribeTest();
4048

4149
System.out.println("\nEverything seems to be alright.");
@@ -77,15 +85,15 @@ private static void testParse() throws IOException {
7785
"01234\r\n56789"
7886
);
7987

80-
List arr = (List) new Parser(new ByteArrayInputStream("*5\r\n:1\r\n:2\r\n:3\r\n:4\r\n:5\r\n".getBytes())).parse();
88+
List<?> arr = (List<?>) new Parser(new ByteArrayInputStream("*5\r\n:1\r\n:2\r\n:3\r\n:4\r\n:5\r\n".getBytes())).parse();
8189
assertEqual(arr.size(), 5);
8290
assertEqual((Long) arr.get(0), 1);
8391
assertEqual((Long) arr.get(1), 2);
8492
assertEqual((Long) arr.get(2), 3);
8593
assertEqual((Long) arr.get(3), 4);
8694
assertEqual((Long) arr.get(4), 5);
8795

88-
List arr2 = (List) new Parser(new ByteArrayInputStream("*1\r\n$5\r\n12345\r\n".getBytes())).parse();
96+
List<?> arr2 = (List<?>) new Parser(new ByteArrayInputStream("*1\r\n$5\r\n12345\r\n".getBytes())).parse();
8997
assertEqual(arr2.size(), 1);
9098
assertEqual(new String((byte[])arr2.get(0)), "12345");
9199
System.out.println("Tests passed successfully: testParse");
@@ -95,7 +103,7 @@ private static void integrationTest() throws InterruptedException {
95103
final String keyName = RedisTest.class.getCanonicalName();
96104
Consumer<Redis.FailableConsumer<Redis, IOException>> exec = (consumer) -> {
97105
try {
98-
Redis.run(consumer, "127.0.0.1", 6379);
106+
Redis.run(consumer, "127.0.0.1", REDIS_PORT);
99107
} catch (IOException e) {
100108
e.printStackTrace();
101109
throw new RuntimeException(e);
@@ -142,7 +150,7 @@ private static void integrationTest() throws InterruptedException {
142150

143151
exec.accept(
144152
(redis) -> {
145-
redis = new Redis(new Socket("127.0.0.1", 6379));
153+
redis = new Redis(new Socket("127.0.0.1", REDIS_PORT));
146154
List<Object> result = redis.pipeline()
147155
.call("INCR", keyName)
148156
.call("INCR", keyName)
@@ -174,18 +182,16 @@ private static void integrationTest() throws InterruptedException {
174182
assertEqual("QUEUED", new String((byte[])result.get(2)));
175183
assertEqual("QUEUED", new String((byte[])result.get(3)));
176184
assertEqual("QUEUED", new String((byte[])result.get(4)));
177-
assertEqual(1, (Long) ((List<Object>) result.get(5)).get(0));
178-
assertEqual(2, (Long) ((List<Object>) result.get(5)).get(1));
179-
assertEqual(3, (Long) ((List<Object>) result.get(5)).get(2));
180-
assertEqual(4, (Long) ((List<Object>) result.get(5)).get(3));
185+
assertEqual(1, (Long) ((List<?>) result.get(5)).get(0));
186+
assertEqual(2, (Long) ((List<?>) result.get(5)).get(1));
187+
assertEqual(3, (Long) ((List<?>) result.get(5)).get(2));
188+
assertEqual(4, (Long) ((List<?>) result.get(5)).get(3));
181189
redis.call("DEL", keyName);
182190
}
183191
);
184192

185193
exec.accept(
186-
(redis) -> {
187-
redis.call("INFO");
188-
}
194+
(redis) -> redis.call("INFO")
189195
);
190196

191197
// This test checks if `call` will return null from a disconnected connection.
@@ -221,10 +227,7 @@ private static void integrationTest() throws InterruptedException {
221227
});
222228
}
223229

224-
private static void bufferSizePerformanceTest(int numBitsFrom, int numBitsTo) throws IOException, InterruptedException {
225-
final int numThreads = 200;
226-
final int numMessages = 25000;
227-
230+
private static void bufferSizePerformanceTest() throws IOException, InterruptedException {
228231
// Test in- and output buffer sizes.
229232
for (Map.Entry<MessageProducerTypeName, Supplier<String>> type : messageProducerTypes.entrySet()) {
230233
for (int ab = 0; ab <= 1; ab++) {
@@ -246,9 +249,9 @@ private static void bufferSizePerformanceTest(int numBitsFrom, int numBitsTo) th
246249
() -> {
247250
try {
248251
if (isInputBufferTest) {
249-
return new Redis(new Socket("127.0.0.1", 6379), bufSize, 1 << 16);
252+
return new Redis(new Socket("127.0.0.1", REDIS_PORT), bufSize, 1 << 16);
250253
} else {
251-
return new Redis(new Socket("127.0.0.1", 6379), 1 << 16, bufSize);
254+
return new Redis(new Socket("127.0.0.1", REDIS_PORT), 1 << 16, bufSize);
252255
}
253256
} catch (IOException e) {
254257
e.printStackTrace();
@@ -280,11 +283,11 @@ private static void socketManagementPerformanceTest() throws IOException, Interr
280283
try {
281284
if (isThreadLocalTest) {
282285
if (redis.get() == null) {
283-
redis.set(new Redis(new Socket("127.0.0.1", 6379)));
286+
redis.set(new Redis(new Socket("127.0.0.1", REDIS_PORT)));
284287
}
285288
return redis.get();
286289
}
287-
return new Redis(new Socket("127.0.0.1", 6379));
290+
return new Redis(new Socket("127.0.0.1", REDIS_PORT));
288291
} catch (IOException e) {
289292
e.printStackTrace();
290293
}
@@ -325,7 +328,7 @@ private static void performanceTest(String description, int numThreads, int numM
325328
try {
326329
Redis redis2 = connector.get();
327330
for (int n = 0; n < numMessages / numThreads; n++) {
328-
List value = redis2.call("BLPOP", queueKeyName, "0");
331+
List<?> value = redis2.call("BLPOP", queueKeyName, "0");
329332
assertTrue(value.get(1) instanceof byte[]);
330333
size.addAndGet(((byte[])value.get(1)).length);
331334
count.incrementAndGet();
@@ -361,10 +364,8 @@ public static void binaryTest() throws IOException {
361364

362365
Redis.run((redis) -> {
363366
redis.call("SET", "foo", bytes);
364-
System.out.printf("Byte length: %d", redis.<byte[]>call("GET", "foo").length);
365-
366-
// assertTrue(redis.<String>call("GET", "foo").getBytes().length == 1024);
367-
}, "localhost", 6379);
367+
assertEqual(1024, redis.<byte[]>call("GET", "foo").length);
368+
}, REDIS_HOST, REDIS_PORT);
368369
}
369370

370371
public static void managedTest() throws IOException {
@@ -374,7 +375,7 @@ public static void managedTest() throws IOException {
374375
Redis.run((r) -> {
375376
String response = new String(r.<byte[]>call("CLIENT", "LIST", "TYPE", "normal"));
376377
numClients.set(response.split("\n").length);
377-
}, "localhost", 6379);
378+
}, REDIS_HOST, REDIS_PORT);
378379
} catch (IOException e) {
379380
throw new RuntimeException(e);
380381
}
@@ -384,7 +385,7 @@ public static void managedTest() throws IOException {
384385
};
385386

386387
int before = countClients.get();
387-
try (Redis.Managed r = Redis.connect("localhost", 6379)) {
388+
try (Redis.Managed r = Redis.connect(REDIS_HOST, REDIS_PORT)) {
388389
if (countClients.get() <= before) {
389390
throw new IllegalStateException("Expected number of connected clients to be less than " + before);
390391
}
@@ -400,16 +401,14 @@ public static void subscribeTest() throws IOException, InterruptedException {
400401

401402
ExecutorService s = Executors.newFixedThreadPool(2);
402403
Redis.run(
403-
redis -> {
404-
redis.call("CONFIG", "SET", "notify-keyspace-events", "AKE");
405-
}, "localhost", 6379
404+
redis -> redis.call("CONFIG", "SET", "notify-keyspace-events", "AKE"), REDIS_HOST, REDIS_PORT
406405
);
407406
AtomicInteger n = new AtomicInteger(0);
408407

409408
s.submit(() -> {
410409
try {
411410
System.out.println("Subscription starting");
412-
Socket timeoutSocket = new Socket("localhost", 6379);
411+
Socket timeoutSocket = new Socket(REDIS_HOST, REDIS_PORT);
413412
timeoutSocket.setSoTimeout(1500);
414413
try {
415414
Redis.run(redis -> {
@@ -454,7 +453,7 @@ public static void subscribeTest() throws IOException, InterruptedException {
454453
} catch (InterruptedException e) {
455454
e.printStackTrace();
456455
}
457-
}, "localhost", 6379);
456+
}, REDIS_HOST, REDIS_PORT);
458457
} catch (IOException e) {
459458
e.printStackTrace();
460459
}
@@ -548,13 +547,11 @@ enum MessageProducerTypeName {
548547
final String small = msg.substring(0, 256);
549548
final String larger = msg;
550549
final AtomicInteger rotate = new AtomicInteger(0);
551-
final String large = (((Supplier<String>) () -> {
552-
StringBuilder tmp = new StringBuilder();
553-
for (int i = 0; i < 10; i++) {
554-
tmp.append(msg);
555-
}
556-
return tmp.toString();
557-
}).get());
550+
StringBuilder tmp = new StringBuilder();
551+
for (int i = 0; i < 10; i++) {
552+
tmp.append(msg);
553+
}
554+
final String large = (tmp.toString());
558555

559556
strings = new String[]{
560557
small, larger, large

0 commit comments

Comments
 (0)