Java 16 migration for Redis examples.

See #606.
This commit is contained in:
Mark Paluch
2021-04-29 11:03:21 +02:00
parent 338d9d92ca
commit 88aabe89e2
16 changed files with 77 additions and 98 deletions

View File

@@ -15,10 +15,6 @@
*/
package example.springdata.redis.cluster;
import static org.hamcrest.core.Is.*;
import static org.hamcrest.core.IsCollectionContaining.*;
import static org.junit.Assert.*;
import example.springdata.redis.test.util.RequiresRedisServer;
import java.util.Arrays;
@@ -36,6 +32,8 @@ import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* {@link BasicUsageTests} shows general usage of {@link RedisTemplate} and {@link RedisOperations} in a clustered
* environment.
@@ -54,13 +52,9 @@ public class BasicUsageTests {
@Before
public void setUp() {
template.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "FLUSHED";
}
template.execute((RedisCallback<String>) connection -> {
connection.flushDb();
return "FLUSHED";
});
}
@@ -72,7 +66,7 @@ public class BasicUsageTests {
public void singleSlotOperation() {
template.opsForValue().set("name", "rand al'thor"); // slot 5798
assertThat(template.opsForValue().get("name"), is("rand al'thor"));
assertThat(template.opsForValue().get("name")).isEqualTo("rand al'thor");
}
/**
@@ -86,8 +80,8 @@ public class BasicUsageTests {
template.opsForValue().set("name", "matrim cauthon"); // slot 5798
template.opsForValue().set("nickname", "prince of the ravens"); // slot 14594
assertThat(template.opsForValue().multiGet(Arrays.asList("name", "nickname")),
hasItems("matrim cauthon", "prince of the ravens"));
assertThat(template.opsForValue().multiGet(Arrays.asList("name", "nickname"))).contains("matrim cauthon",
"prince of the ravens");
}
/**
@@ -100,8 +94,8 @@ public class BasicUsageTests {
template.opsForValue().set("{user}.name", "perrin aybara"); // slot 5474
template.opsForValue().set("{user}.nickname", "wolfbrother"); // slot 5474
assertThat(template.opsForValue().multiGet(Arrays.asList("{user}.name", "{user}.nickname")),
hasItems("perrin aybara", "wolfbrother"));
assertThat(template.opsForValue().multiGet(Arrays.asList("{user}.name", "{user}.nickname")))
.contains("perrin aybara", "wolfbrother");
}
/**
@@ -117,6 +111,6 @@ public class BasicUsageTests {
template.opsForValue().set("nickname", "dragon reborn"); // slot 14594
template.opsForValue().set("age", "23"); // slot 741;
assertThat(template.keys("*"), hasItems("name", "nickname", "age"));
assertThat(template.keys("*")).contains("name", "nickname", "age");
}
}

View File

@@ -68,12 +68,12 @@ public class GeoOperationsTests {
@Test
public void geoRadiusByMember() {
GeoResults<GeoLocation<String>> byDistance = geoOperations.geoRadiusByMember("Sicily", "Palermo",
var byDistance = geoOperations.geoRadiusByMember("Sicily", "Palermo",
new Distance(100, DistanceUnit.KILOMETERS));
assertThat(byDistance).hasSize(2).extracting("content.name").contains("Arigento", "Palermo");
GeoResults<GeoLocation<String>> greaterDistance = geoOperations.geoRadiusByMember("Sicily", "Palermo",
var greaterDistance = geoOperations.geoRadiusByMember("Sicily", "Palermo",
new Distance(200, DistanceUnit.KILOMETERS));
assertThat(greaterDistance).hasSize(3).extracting("content.name").contains("Arigento", "Catania", "Palermo");
@@ -85,9 +85,9 @@ public class GeoOperationsTests {
@Test
public void geoRadius() {
Circle circle = new Circle(new Point(13.583333, 37.316667), //
var circle = new Circle(new Point(13.583333, 37.316667), //
new Distance(100, DistanceUnit.KILOMETERS));
GeoResults<GeoLocation<String>> result = geoOperations.geoRadius("Sicily", circle);
var result = geoOperations.geoRadius("Sicily", circle);
assertThat(result).hasSize(2).extracting("content.name").contains("Arigento", "Palermo");
}
@@ -98,7 +98,7 @@ public class GeoOperationsTests {
@Test
public void geoDistance() {
Distance distance = geoOperations.geoDist("Sicily", "Catania", "Palermo", DistanceUnit.KILOMETERS);
var distance = geoOperations.geoDist("Sicily", "Catania", "Palermo", DistanceUnit.KILOMETERS);
assertThat(distance.getValue()).isBetween(130d, 140d);
}
@@ -109,7 +109,7 @@ public class GeoOperationsTests {
@Test
public void geoHash() {
List<String> geohashes = geoOperations.geoHash("Sicily", "Catania", "Palermo");
var geohashes = geoOperations.geoHash("Sicily", "Catania", "Palermo");
assertThat(geohashes).hasSize(2).contains("sqdtr74hyu0", "sq9sm1716e0");
}

View File

@@ -70,8 +70,7 @@ public class KeyOperationsTests {
generateRandomKeys(1000);
Set<byte[]> keys = this.connection.keys(serializer.serialize(KEY_PATTERN));
printKeys(keys.iterator());
var keys = this.connection.keys(serializer.serialize(KEY_PATTERN));
}
/**
@@ -85,23 +84,12 @@ public class KeyOperationsTests {
generateRandomKeys(1000);
Cursor<byte[]> cursor = this.connection.scan(ScanOptions.scanOptions().match(KEY_PATTERN).build());
printKeys(cursor);
}
private void printKeys(Iterator<byte[]> keys) {
int i = 0;
while (keys.hasNext()) {
System.out.println(new String(keys.next()));
i++;
}
System.out.println(String.format("Total No. found: %s", i));
this.connection.scan(ScanOptions.scanOptions().match(KEY_PATTERN).build());
}
private void generateRandomKeys(int nrKeys) {
for (int i = 0; i < nrKeys; i++) {
for (var i = 0; i < nrKeys; i++) {
this.connection.set((PREFIX + "-" + i).getBytes(), UUID.randomUUID().toString().getBytes());
}
}

View File

@@ -26,9 +26,6 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
*
* @author Mark Paluch
*/
@Value
@RequiredArgsConstructor
@JsonTypeInfo(use = Id.CLASS, property = "_type")
public class EmailAddress {
final String address;
public record EmailAddress(String address) {
}

View File

@@ -51,11 +51,11 @@ public class RedisTestConfiguration {
public ReactiveRedisTemplate<String, Person> reactiveJsonPersonRedisTemplate(
ReactiveRedisConnectionFactory connectionFactory) {
Jackson2JsonRedisSerializer<Person> serializer = new Jackson2JsonRedisSerializer<>(Person.class);
var serializer = new Jackson2JsonRedisSerializer<Person>(Person.class);
RedisSerializationContextBuilder<String, Person> builder = RedisSerializationContext
.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Person> serializationContext = builder.value(serializer).build();
var serializationContext = builder.value(serializer).build();
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
}
@@ -70,7 +70,7 @@ public class RedisTestConfiguration {
RedisSerializationContextBuilder<String, Object> builder = RedisSerializationContext
.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Object> serializationContext = builder
var serializationContext = builder
.value(new GenericJackson2JsonRedisSerializer("_type")).build();
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);

View File

@@ -77,7 +77,7 @@ public class KeyCommandsTests {
generateRandomKeys(50);
Mono<Long> keyCount = connection.keyCommands() //
var keyCount = connection.keyCommands() //
.keys(ByteBuffer.wrap(serializer.serialize(KEY_PATTERN))) //
.flatMapMany(Flux::fromIterable) //
.doOnNext(byteBuffer -> System.out.println(toString(byteBuffer))) //
@@ -93,12 +93,12 @@ public class KeyCommandsTests {
@Test
public void storeToListAndPop() {
Mono<PopResult> popResult = connection.listCommands()
var popResult = connection.listCommands()
.brPop(Collections.singletonList(ByteBuffer.wrap("list".getBytes())), Duration.ofSeconds(5));
Mono<Long> llen = connection.listCommands().lLen(ByteBuffer.wrap("list".getBytes()));
var llen = connection.listCommands().lLen(ByteBuffer.wrap("list".getBytes()));
Mono<Long> popAndLlen = connection.listCommands() //
var popAndLlen = connection.listCommands() //
.rPush(ByteBuffer.wrap("list".getBytes()), Collections.singletonList(ByteBuffer.wrap("item".getBytes())))
.flatMap(l -> popResult) //
.doOnNext(result -> System.out.println(toString(result.getValue()))) //
@@ -110,9 +110,9 @@ public class KeyCommandsTests {
private void generateRandomKeys(int nrKeys) {
Flux<String> keyFlux = Flux.range(0, nrKeys).map(i -> (PREFIX + "-" + i));
var keyFlux = Flux.range(0, nrKeys).map(i -> (PREFIX + "-" + i));
Flux<SetCommand> generator = keyFlux.map(String::getBytes).map(ByteBuffer::wrap) //
var generator = keyFlux.map(String::getBytes).map(ByteBuffer::wrap) //
.map(key -> SetCommand.set(key) //
.value(ByteBuffer.wrap(UUID.randomUUID().toString().getBytes())));

View File

@@ -66,7 +66,7 @@ public class JacksonJsonTests {
.expectNext(true) //
.verifyComplete();
Flux<String> get = typedOperations.execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("homer".getBytes()))) //
var get = typedOperations.execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("homer".getBytes()))) //
.map(ByteUtils::getBytes) //
.map(String::new);
@@ -93,7 +93,7 @@ public class JacksonJsonTests {
.expectNext(true) //
.verifyComplete();
Flux<String> get = genericOperations.execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("homer".getBytes()))) //
var get = genericOperations.execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("homer".getBytes()))) //
.map(ByteUtils::getBytes) //
.map(String::new);
@@ -121,7 +121,7 @@ public class JacksonJsonTests {
.expectNext(true) //
.verifyComplete();
Flux<String> get = genericOperations.execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("mail".getBytes()))) //
var get = genericOperations.execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("mail".getBytes()))) //
.map(ByteUtils::getBytes) //
.map(String::new);

View File

@@ -60,11 +60,11 @@ public class ListOperationsTests {
@Test
public void shouldPollAndPopulateQueue() {
String queue = "foo";
var queue = "foo";
ReactiveListOperations<String, String> listOperations = operations.opsForList();
var listOperations = operations.opsForList();
Mono<String> blpop = listOperations //
var blpop = listOperations //
.leftPop(queue, Duration.ofSeconds(30)) //
.log("example.springdata.redis", Level.INFO);

View File

@@ -61,11 +61,11 @@ public class ValueOperationsTests {
@Test
public void shouldCacheValue() {
String cacheKey = "foo";
var cacheKey = "foo";
ReactiveValueOperations<String, String> valueOperations = operations.opsForValue();
var valueOperations = operations.opsForValue();
Mono<String> cachedMono = valueOperations.get(cacheKey) //
var cachedMono = valueOperations.get(cacheKey) //
.switchIfEmpty(cacheValue().flatMap(it -> {
return valueOperations.set(cacheKey, it, Duration.ofSeconds(60)).then(Mono.just(it));
@@ -80,7 +80,7 @@ public class ValueOperationsTests {
log.info("Subsequent access (use cached value)");
Duration duration = StepVerifier.create(cachedMono) //
var duration = StepVerifier.create(cachedMono) //
.expectNext("Hello, World!") //
.verifyComplete();

View File

@@ -114,7 +114,7 @@ public class PersonRepositoryTests {
flushTestUsers();
List<Person> starks = repository.findByLastname(eddard.getLastname());
var starks = repository.findByLastname(eddard.getLastname());
assertThat(starks).contains(eddard, robb, sansa, arya, bran, rickon).doesNotContain(jon);
}
@@ -127,7 +127,7 @@ public class PersonRepositoryTests {
flushTestUsers();
List<Person> aryaStark = repository.findByFirstnameAndLastname(arya.getFirstname(), arya.getLastname());
var aryaStark = repository.findByFirstnameAndLastname(arya.getFirstname(), arya.getLastname());
assertThat(aryaStark).containsOnly(arya);
}
@@ -140,7 +140,7 @@ public class PersonRepositoryTests {
flushTestUsers();
List<Person> aryaAndJon = repository.findByFirstnameOrLastname(arya.getFirstname(), jon.getLastname());
var aryaAndJon = repository.findByFirstnameOrLastname(arya.getFirstname(), jon.getLastname());
assertThat(aryaAndJon).containsOnly(arya, jon);
}
@@ -153,9 +153,9 @@ public class PersonRepositoryTests {
flushTestUsers();
Example<Person> example = Example.of(new Person(null, "stark", null));
var example = Example.of(new Person(null, "stark", null));
Iterable<Person> starks = repository.findAll(example);
var starks = repository.findAll(example);
assertThat(starks).contains(arya, eddard).doesNotContain(jon);
}
@@ -168,12 +168,12 @@ public class PersonRepositoryTests {
flushTestUsers();
Page<Person> page1 = repository.findPersonByLastname(eddard.getLastname(), PageRequest.of(0, 5));
var page1 = repository.findPersonByLastname(eddard.getLastname(), PageRequest.of(0, 5));
assertThat(page1.getNumberOfElements()).isEqualTo(5);
assertThat(page1.getTotalElements()).isEqualTo(6);
Page<Person> page2 = repository.findPersonByLastname(eddard.getLastname(), PageRequest.of(1, 5));
var page2 = repository.findPersonByLastname(eddard.getLastname(), PageRequest.of(1, 5));
assertThat(page2.getNumberOfElements()).isEqualTo(1);
assertThat(page2.getTotalElements()).isEqualTo(6);
@@ -185,7 +185,7 @@ public class PersonRepositoryTests {
@Test
public void findByEmbeddedProperty() {
Address winterfell = new Address();
var winterfell = new Address();
winterfell.setCountry("the north");
winterfell.setCity("winterfell");
@@ -193,7 +193,7 @@ public class PersonRepositoryTests {
flushTestUsers();
List<Person> eddardStark = repository.findByAddress_City(winterfell.getCity());
var eddardStark = repository.findByAddress_City(winterfell.getCity());
assertThat(eddardStark).containsOnly(eddard);
}
@@ -204,14 +204,14 @@ public class PersonRepositoryTests {
@Test
public void findByGeoLocationProperty() {
Address winterfell = new Address();
var winterfell = new Address();
winterfell.setCountry("the north");
winterfell.setCity("winterfell");
winterfell.setLocation(new Point(52.9541053, -1.2401016));
eddard.setAddress(winterfell);
Address casterlystein = new Address();
var casterlystein = new Address();
casterlystein.setCountry("Westerland");
casterlystein.setCity("Casterlystein");
casterlystein.setLocation(new Point(51.5287352, -0.3817819));
@@ -220,13 +220,13 @@ public class PersonRepositoryTests {
flushTestUsers();
Circle innerCircle = new Circle(new Point(51.8911912, -0.4979756), new Distance(50, Metrics.KILOMETERS));
List<Person> eddardStark = repository.findByAddress_LocationWithin(innerCircle);
var innerCircle = new Circle(new Point(51.8911912, -0.4979756), new Distance(50, Metrics.KILOMETERS));
var eddardStark = repository.findByAddress_LocationWithin(innerCircle);
assertThat(eddardStark).containsOnly(robb);
Circle biggerCircle = new Circle(new Point(51.8911912, -0.4979756), new Distance(200, Metrics.KILOMETERS));
List<Person> eddardAndRobbStark = repository.findByAddress_LocationWithin(biggerCircle);
var biggerCircle = new Circle(new Point(51.8911912, -0.4979756), new Distance(200, Metrics.KILOMETERS));
var eddardAndRobbStark = repository.findByAddress_LocationWithin(biggerCircle);
assertThat(eddardAndRobbStark).hasSize(2).contains(robb, eddard);
}

View File

@@ -48,16 +48,16 @@ public class RedisSentinelApplication {
ApplicationContext context = SpringApplication.run(RedisSentinelApplication.class, args);
StringRedisTemplate template = context.getBean(StringRedisTemplate.class);
var template = context.getBean(StringRedisTemplate.class);
template.opsForValue().set("loop-forever", "0");
StopWatch stopWatch = new StopWatch();
var stopWatch = new StopWatch();
while (true) {
try {
String value = "IT:= " + template.opsForValue().increment("loop-forever", 1);
var value = "IT:= " + template.opsForValue().increment("loop-forever", 1);
printBackFromErrorStateInfoIfStopWatchIsRunning(stopWatch);
System.out.println(value);

View File

@@ -113,7 +113,7 @@ public class ReactiveStreamApiTests {
@Test
public void continuousRead() {
Flux<MapRecord<String, String, String>> messages = streamReceiver.receive(fromStart(SensorData.KEY));
var messages = streamReceiver.receive(fromStart(SensorData.KEY));
messages.as(StepVerifier::create)
.then(() ->

View File

@@ -67,10 +67,10 @@ public class SyncStreamApiTests {
public void basics() {
// XADD with fixed id
RecordId fixedId1 = streamOps.add(SensorData.RECORD_1234_0);
var fixedId1 = streamOps.add(SensorData.RECORD_1234_0);
assertThat(fixedId1).isEqualTo(SensorData.RECORD_1234_0.getId());
RecordId fixedId2 = streamOps.add(SensorData.RECORD_1234_1);
var fixedId2 = streamOps.add(SensorData.RECORD_1234_1);
assertThat(fixedId2).isEqualTo(SensorData.RECORD_1234_1.getId());
// XLEN
@@ -82,17 +82,17 @@ public class SyncStreamApiTests {
}).withMessageContaining("ID specified");
// XADD with autogenerated id
RecordId autogeneratedId = streamOps.add(SensorData.create("1234", "19.8", null));
var autogeneratedId = streamOps.add(SensorData.create("1234", "19.8", null));
assertThat(autogeneratedId.getValue()).endsWith("-0");
assertThat(streamOps.size(SensorData.KEY)).isEqualTo(3L);
// XREAD from start
List<MapRecord<String, String, String>> fromStart = streamOps.read(fromStart(SensorData.KEY));
var fromStart = streamOps.read(fromStart(SensorData.KEY));
assertThat(fromStart).hasSize(3).extracting(MapRecord::getId).containsExactly(fixedId1, fixedId2, autogeneratedId);
// XREAD resume after
List<MapRecord<String, String, String>> fromOffset = streamOps.read(StreamOffset.create(SensorData.KEY, ReadOffset.from(fixedId2)));
var fromOffset = streamOps.read(StreamOffset.create(SensorData.KEY, ReadOffset.from(fixedId2)));
assertThat(fromOffset).hasSize(1).extracting(MapRecord::getId).containsExactly(autogeneratedId);
}
@@ -104,7 +104,7 @@ public class SyncStreamApiTests {
messageListenerContainer.start();
}
CapturingStreamListener streamListener = CapturingStreamListener.create();
var streamListener = CapturingStreamListener.create();
// XREAD BLOCK
messageListenerContainer.receive(fromStart(SensorData.KEY), streamListener);

View File

@@ -41,9 +41,9 @@ class ManagedClientResources {
*/
static ClientResources getClientResources() {
AtomicReference<ClientResources> ref = instance.clientResources;
var ref = instance.clientResources;
ClientResources clientResources = ref.get();
var clientResources = ref.get();
if (clientResources != null) {
return clientResources;
}

View File

@@ -134,8 +134,8 @@ public class RequiresRedisSentinel implements TestRule {
private void verify(SentinelsAvailable verificationMode) {
int failed = 0;
for (RedisNode node : sentinelConfig.getSentinels()) {
var failed = 0;
for (var node : sentinelConfig.getSentinels()) {
if (!isAvailable(node)) {
failed++;
}
@@ -163,10 +163,10 @@ public class RequiresRedisSentinel implements TestRule {
private boolean isAvailable(RedisNode node) {
RedisClient redisClient = RedisClient.create(ManagedClientResources.getClientResources(),
var redisClient = RedisClient.create(ManagedClientResources.getClientResources(),
RedisURI.create(node.getHost(), node.getPort()));
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
try (var connection = redisClient.connect()) {
connection.sync().ping();
} catch (Exception e) {
return false;

View File

@@ -98,7 +98,7 @@ public class RequiresRedisServer extends ExternalResource {
@Override
protected void before() throws Throwable {
try (Socket socket = new Socket()) {
try (var socket = new Socket()) {
socket.setTcpNoDelay(true);
socket.setSoLinger(true, 0);
socket.connect(new InetSocketAddress(host, port), timeout);
@@ -110,14 +110,14 @@ public class RequiresRedisServer extends ExternalResource {
return;
}
RedisClient redisClient = RedisClient.create(ManagedClientResources.getClientResources(),
var redisClient = RedisClient.create(ManagedClientResources.getClientResources(),
RedisURI.create(host, port));
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
try (var connection = redisClient.connect()) {
String infoServer = connection.sync().info("server");
String redisVersion = LettuceConverters.stringToProps().convert(infoServer).getProperty("redis_version");
Version runningVersion = Version.parse(redisVersion);
var infoServer = connection.sync().info("server");
var redisVersion = LettuceConverters.stringToProps().convert(infoServer).getProperty("redis_version");
var runningVersion = Version.parse(redisVersion);
if (runningVersion.isLessThan(requiredVersion)) {
throw new AssumptionViolatedException(String