GH-3840: Migrate Redis tests to Testcontainers

Fixes https://github.com/spring-projects/spring-integration/issues/3840

* Create a new abstraction `RedisTest` for Testcontainers-based tests
* Move existing common utility methods to the new interface
* Migrate all existing Redis tests to use this new `RedisTest` interface
* Migrate all existing Redis tests to JUnit5
* Make all existing Redis tests confirming to JUnit5 standards, such as
default methods and classes visibility instead of public
* Add a dependency for parametrized tests in JUnit5
* Improve assertions readability across tests, for instance:
assertThat(thing.size()).isEqualTo(2) -> assertThat(thing).hasSize(2)
* Add real assertions to
`RedisLockRegistryTests.twoRedisLockRegistryTest` (earlier it did not
have assertions at all)
* Reformat, rearrange and cleanup the code
* Fix a couple of small changes after the code review:
* Change base interface name to be consistent with other similar places
* Typo in javadocs
* Small tests readability improvement regarding assertions
* Add `opens java.util` to `spring-integration-redis`
 to satisfy a `ReactiveRedisStreamMessageHandlerTests.testMessageWithListPayload()`
 requirements
This commit is contained in:
Artem Vozhdayenko
2022-07-14 06:19:29 -04:00
committed by Artem Bilan
parent 79d31b2329
commit 1c461a3e2c
44 changed files with 1155 additions and 1372 deletions

View File

@@ -107,7 +107,7 @@ ext {
springSecurityVersion = project.hasProperty('springSecurityVersion') ? project.springSecurityVersion : '6.0.0-SNAPSHOT'
springVersion = project.hasProperty('springVersion') ? project.springVersion : '6.0.0-SNAPSHOT'
springWsVersion = '4.0.0-SNAPSHOT'
testcontainersVersion = '1.17.1'
testcontainersVersion = '1.17.3'
tomcatVersion = '10.0.21'
xmlUnitVersion = '2.9.0'
xstreamVersion = '1.4.19'
@@ -260,6 +260,7 @@ configure(javaProjects) { subproject ->
exclude group: 'org.hamcrest'
}
testImplementation 'org.junit.jupiter:junit-jupiter-api'
testImplementation 'org.junit.jupiter:junit-jupiter-params'
testImplementation("com.willowtreeapps.assertk:assertk-jvm:$assertkVersion") {
exclude group: 'org.jetbrains.kotlin'
}
@@ -839,6 +840,10 @@ project('spring-integration-redis') {
testImplementation "org.hamcrest:hamcrest-core:$hamcrestVersion"
testImplementation 'com.fasterxml.jackson.core:jackson-databind'
}
tasks.withType(JavaForkOptions) {
jvmArgs '--add-opens', 'java.base/java.util=ALL-UNNAMED'
}
}
project('spring-integration-rsocket') {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,17 +28,18 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.geode.cache.CacheFactory;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.gemfire.metadata.GemfireMetadataStore;
import org.springframework.integration.jdbc.metadata.JdbcMetadataStore;
import org.springframework.integration.metadata.ConcurrentMetadataStore;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.metadata.RedisMetadataStore;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
@@ -48,23 +49,30 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
* @author Gary Russell
* @author Artem Bilan
* @author Bojan Vukasovic
* @author Artem Vozhdayenko
*
* @since 4.0
*
*/
public class PersistentAcceptOnceFileListFilterExternalStoreTests extends RedisAvailableTests {
public class PersistentAcceptOnceFileListFilterExternalStoreTests implements RedisContainerTest {
static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnectionFactory() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
public void testFileSystemWithRedisMetadataStore() throws Exception {
RedisTemplate<String, ?> template = new RedisTemplate<>();
template.setConnectionFactory(this.getConnectionFactoryForTest());
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
template.delete("persistentAcceptOnceFileListFilterRedisTests");
try {
this.testFileSystem(new RedisMetadataStore(this.getConnectionFactoryForTest(),
this.testFileSystem(new RedisMetadataStore(redisConnectionFactory,
"persistentAcceptOnceFileListFilterRedisTests"));
}
finally {
@@ -95,8 +103,8 @@ public class PersistentAcceptOnceFileListFilterExternalStoreTests extends RedisA
List<Map<String, Object>> metaData = new JdbcTemplate(dataSource)
.queryForList("SELECT * FROM INT_METADATA_STORE");
assertThat(metaData.size()).isEqualTo(1);
assertThat(metaData.get(0).get("METADATA_VALUE")).isEqualTo("43");
assertThat(metaData).hasSize(1);
assertThat(metaData.get(0)).containsEntry("METADATA_VALUE", "43");
}
finally {
dataSource.shutdown();
@@ -127,28 +135,28 @@ public class PersistentAcceptOnceFileListFilterExternalStoreTests extends RedisA
final FileSystemPersistentAcceptOnceFileListFilter filter =
new FileSystemPersistentAcceptOnceFileListFilter(store, "foo:");
final File file = File.createTempFile("foo", ".txt");
assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(1);
assertThat(filter.filterFiles(new File[] {file})).hasSize(1);
String ts = store.get("foo:" + file.getAbsolutePath());
assertThat(ts).isEqualTo(String.valueOf(file.lastModified()));
assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(0);
file.setLastModified(file.lastModified() + 5000L);
assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(1);
assertThat(filter.filterFiles(new File[] {file})).isEmpty();
assertThat(file.setLastModified(file.lastModified() + 5000L)).isTrue();
assertThat(filter.filterFiles(new File[] {file})).hasSize(1);
ts = store.get("foo:" + file.getAbsolutePath());
assertThat(ts).isEqualTo(String.valueOf(file.lastModified()));
assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(0);
assertThat(filter.filterFiles(new File[] {file})).isEmpty();
suspend.set(true);
file.setLastModified(file.lastModified() + 5000L);
assertThat(file.setLastModified(file.lastModified() + 5000L)).isTrue();
Future<Integer> result = Executors.newSingleThreadExecutor()
.submit(() -> filter.filterFiles(new File[] { file }).size());
.submit(() -> filter.filterFiles(new File[] {file}).size());
assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue();
store.put("foo:" + file.getAbsolutePath(), "43");
latch1.countDown();
Integer theResult = result.get(10, TimeUnit.SECONDS);
assertThat(theResult).isEqualTo(Integer.valueOf(0)); // lost the race, key changed
file.delete();
assertThat(file.delete()).isTrue();
filter.close();
}

View File

@@ -14,16 +14,21 @@
* limitations under the License.
*/
package org.springframework.integration.redis.rules;
package org.springframework.integration.redis;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import java.time.Duration;
import org.junit.jupiter.api.BeforeAll;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
@@ -33,36 +38,64 @@ import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
/**
* The base contract for all tests requiring a Redis connection.
* The Testcontainers 'reuse' option must be disabled, so, Ryuk container is started
* and will clean all the containers up from this test suite after JVM exit.
* Since the Redis container instance is shared via static property, it is going to be
* started only once per JVM, therefore the target Docker container is reused automatically.
*
* @author Artem Vozhdayenko
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
*
* @since 6.0
*/
public abstract class RedisAvailableTests {
@Testcontainers(disabledWithoutDocker = true)
public interface RedisContainerTest {
@Rule
public RedisAvailableRule redisAvailableRule = new RedisAvailableRule();
GenericContainer<?> REDIS_CONTAINER = new GenericContainer<>("redis:7.0.2")
.withExposedPorts(6379);
@BeforeClass
public static void setupConnectionFactory() {
RedisAvailableRule.setupConnectionFactory();
@BeforeAll
static void startContainer() {
REDIS_CONTAINER.start();
}
@AfterClass
public static void cleanUpConnectionFactoryIfAny() {
RedisAvailableRule.cleanUpConnectionFactoryIfAny();
/**
* A primary method which should be used to connect to the test Redis instance.
* Can be used in any JUnit lifecycle methods if a test class implements this interface.
*/
static LettuceConnectionFactory connectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setPort(REDIS_CONTAINER.getFirstMappedPort());
LettuceClientConfiguration clientConfiguration = LettuceClientConfiguration.builder()
.clientOptions(
ClientOptions.builder()
.socketOptions(
SocketOptions.builder()
.connectTimeout(Duration.ofMillis(10000))
.keepAlive(true)
.build())
.build())
.commandTimeout(Duration.ofSeconds(10000))
.build();
var connectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfiguration);
connectionFactory.afterPropertiesSet();
return connectionFactory;
}
protected RedisConnectionFactory getConnectionFactoryForTest() {
return RedisAvailableRule.connectionFactory;
}
protected void awaitContainerSubscribed(RedisMessageListenerContainer container) throws Exception {
static void awaitContainerSubscribed(RedisMessageListenerContainer container) throws Exception {
awaitContainerSubscribedNoWait(container);
}
private void awaitContainerSubscribedNoWait(RedisMessageListenerContainer container) throws InterruptedException {
static void awaitContainerSubscribedNoWait(RedisMessageListenerContainer container) throws InterruptedException {
RedisConnection connection = null;
int n = 0;
@@ -82,8 +115,8 @@ public abstract class RedisAvailableTests {
assertThat(n < 300).as("RedisMessageListenerContainer Failed to Subscribe").isTrue();
}
protected void awaitContainerSubscribedWithPatterns(RedisMessageListenerContainer container) throws Exception {
this.awaitContainerSubscribed(container);
static void awaitContainerSubscribedWithPatterns(RedisMessageListenerContainer container) throws Exception {
awaitContainerSubscribed(container);
RedisConnection connection = TestUtils.getPropertyValue(container, "subscriber.connection",
RedisConnection.class);
@@ -96,7 +129,7 @@ public abstract class RedisAvailableTests {
Thread.sleep(1000);
}
protected void awaitFullySubscribed(RedisMessageListenerContainer container, RedisTemplate<?, ?> redisTemplate,
static void awaitFullySubscribed(RedisMessageListenerContainer container, RedisTemplate<?, ?> redisTemplate,
String redisChannelName, QueueChannel channel, Object message) throws Exception {
awaitContainerSubscribedNoWait(container);
drain(channel);
@@ -110,13 +143,13 @@ public abstract class RedisAvailableTests {
assertThat(received).as("Container failed to fully start").isNotNull();
}
private void drain(QueueChannel channel) {
static void drain(QueueChannel channel) {
while (channel.receive(0) != null) {
// drain
}
}
protected void prepareList(RedisConnectionFactory connectionFactory) {
static void prepareList(RedisConnectionFactory connectionFactory) {
StringRedisTemplate redisTemplate = createStringRedisTemplate(connectionFactory);
redisTemplate.delete("presidents");
@@ -139,7 +172,7 @@ public abstract class RedisAvailableTests {
ops.rightPush("George Washington");
}
protected void prepareZset(RedisConnectionFactory connectionFactory) {
static void prepareZset(RedisConnectionFactory connectionFactory) {
StringRedisTemplate redisTemplate = createStringRedisTemplate(connectionFactory);
@@ -163,20 +196,19 @@ public abstract class RedisAvailableTests {
ops.add("George Washington", 18);
}
protected void deletePresidents(RedisConnectionFactory connectionFactory) {
this.deleteKey(connectionFactory, "presidents");
static void deletePresidents(RedisConnectionFactory connectionFactory) {
deleteKey(connectionFactory, "presidents");
}
protected void deleteKey(RedisConnectionFactory connectionFactory, String key) {
static void deleteKey(RedisConnectionFactory connectionFactory, String key) {
StringRedisTemplate redisTemplate = createStringRedisTemplate(connectionFactory);
redisTemplate.delete(key);
}
protected StringRedisTemplate createStringRedisTemplate(RedisConnectionFactory connectionFactory) {
static StringRedisTemplate createStringRedisTemplate(RedisConnectionFactory connectionFactory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,14 +26,14 @@ import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.support.GenericMessage;
@@ -43,22 +43,26 @@ import org.springframework.util.ReflectionUtils;
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
* @author Artem Vozhdayenko
* @since 2.0
*/
public class SubscribableRedisChannelTests extends RedisAvailableTests {
class SubscribableRedisChannelTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
public void pubSubChannelTest() throws Exception {
RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest();
void pubSubChannelTest() throws Exception {
SubscribableRedisChannel channel = new SubscribableRedisChannel(connectionFactory, "si.test.channel");
SubscribableRedisChannel channel = new SubscribableRedisChannel(redisConnectionFactory, "si.test.channel");
channel.setBeanFactory(mock(BeanFactory.class));
channel.afterPropertiesSet();
channel.start();
this.awaitContainerSubscribed(TestUtils.getPropertyValue(channel, "container",
RedisContainerTest.awaitContainerSubscribed(TestUtils.getPropertyValue(channel, "container",
RedisMessageListenerContainer.class));
final CountDownLatch latch = new CountDownLatch(3);
@@ -72,11 +76,9 @@ public class SubscribableRedisChannelTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void dispatcherHasNoSubscribersTest() throws Exception {
RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest();
void dispatcherHasNoSubscribersTest() throws Exception {
SubscribableRedisChannel channel = new SubscribableRedisChannel(connectionFactory, "si.test.channel.no.subs");
SubscribableRedisChannel channel = new SubscribableRedisChannel(redisConnectionFactory, "si.test.channel.no.subs");
channel.setBeanName("dhnsChannel");
channel.setBeanFactory(mock(BeanFactory.class));
channel.afterPropertiesSet();

View File

@@ -2,13 +2,11 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int-redis:publish-subscribe-channel id="redisChannel" topic-name="si.test.topic.parser"
serializer="redisSerializer"/>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,35 +21,34 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.channel.SubscribableRedisChannel;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.support.utils.IntegrationUtils;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Gunnar Hillert
* @author Artem Bilan
* @author Artem Vozhdayenko
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisChannelParserTests extends RedisAvailableTests {
class RedisChannelParserTests implements RedisContainerTest {
@Autowired
private SubscribableRedisChannel redisChannel;
@@ -60,21 +59,20 @@ public class RedisChannelParserTests extends RedisAvailableTests {
@Autowired
private ApplicationContext context;
@Before
@BeforeEach
public void setup() {
this.redisChannel.start();
this.redisChannelWithSubLimit.start();
}
@After
@AfterEach
public void tearDown() {
this.redisChannel.stop();
this.redisChannelWithSubLimit.stop();
}
@Test
@RedisAvailable
public void testPubSubChannelConfig() {
void testPubSubChannelConfig() {
RedisConnectionFactory connectionFactory =
TestUtils.getPropertyValue(this.redisChannel, "connectionFactory", RedisConnectionFactory.class);
RedisSerializer<?> redisSerializer = TestUtils.getPropertyValue(redisChannel, "serializer",
@@ -83,20 +81,19 @@ public class RedisChannelParserTests extends RedisAvailableTests {
assertThat(this.context.getBean("redisSerializer")).isEqualTo(redisSerializer);
assertThat(TestUtils.getPropertyValue(redisChannel, "topicName")).isEqualTo("si.test.topic.parser");
assertThat(TestUtils.getPropertyValue(
TestUtils.getPropertyValue(this.redisChannel, "dispatcher"), "maxSubscribers", Integer.class)
TestUtils.getPropertyValue(this.redisChannel, "dispatcher"), "maxSubscribers", Integer.class)
.intValue()).isEqualTo(Integer.MAX_VALUE);
assertThat(TestUtils.getPropertyValue(this.redisChannelWithSubLimit, "dispatcher.maxSubscribers",
Integer.class)
Integer.class)
.intValue()).isEqualTo(1);
Object mbf = this.context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME);
assertThat(TestUtils.getPropertyValue(this.redisChannelWithSubLimit, "messageBuilderFactory")).isSameAs(mbf);
}
@Test
@RedisAvailable
public void testPubSubChannelUsage() throws Exception {
this.awaitContainerSubscribed(TestUtils.getPropertyValue(this.redisChannel, "container",
void testPubSubChannelUsage() throws Exception {
RedisContainerTest.awaitContainerSubscribed(TestUtils.getPropertyValue(this.redisChannel, "container",
RedisMessageListenerContainer.class));
final Message<?> m = new GenericMessage<>("Hello Redis");

View File

@@ -3,14 +3,12 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int-redis:inbound-channel-adapter
id="adapter" topics="foo" topic-patterns="f*, b*" channel="receiveChannel" error-channel="testErrorChannel"

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +20,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.Executor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
@@ -30,16 +29,14 @@ import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.inbound.RedisInboundChannelAdapter;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableRule;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.support.converter.SimpleMessageConverter;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Oleg Zhurakousky
@@ -48,10 +45,11 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Gunnar Hillert
* @author Venil Noronha
* @author Artem Bilan
* @author Artem Vozhdayenko
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisInboundChannelAdapterParserTests extends RedisAvailableTests {
class RedisInboundChannelAdapterParserTests implements RedisContainerTest {
@Autowired
private ApplicationContext context;
@@ -66,8 +64,12 @@ public class RedisInboundChannelAdapterParserTests extends RedisAvailableTests {
@Autowired
private Executor executor;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Test
public void validateConfiguration() {
void validateConfiguration() {
RedisInboundChannelAdapter adapter = context.getBean("adapter", RedisInboundChannelAdapter.class);
assertThat(adapter.getComponentName()).isEqualTo("adapter");
assertThat(adapter.getComponentType()).isEqualTo("redis:inbound-channel-adapter");
@@ -88,17 +90,14 @@ public class RedisInboundChannelAdapterParserTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testInboundChannelAdapterMessaging() throws Exception {
void testInboundChannelAdapterMessaging() throws Exception {
RedisInboundChannelAdapter adapter = context.getBean("adapter", RedisInboundChannelAdapter.class);
adapter.start();
awaitContainerSubscribedWithPatterns(TestUtils.getPropertyValue(adapter, "container",
RedisContainerTest.awaitContainerSubscribedWithPatterns(TestUtils.getPropertyValue(adapter, "container",
RedisMessageListenerContainer.class));
RedisConnectionFactory connectionFactory = RedisAvailableRule.connectionFactory;
connectionFactory.getConnection().publish("foo".getBytes(), "Hello Redis from foo".getBytes());
connectionFactory.getConnection().publish("bar".getBytes(), "Hello Redis from bar".getBytes());
redisConnectionFactory.getConnection().publish("foo".getBytes(), "Hello Redis from foo".getBytes());
redisConnectionFactory.getConnection().publish("bar".getBytes(), "Hello Redis from bar".getBytes());
QueueChannel receiveChannel = context.getBean("receiveChannel", QueueChannel.class);
for (int i = 0; i < 3; i++) {
@@ -111,7 +110,7 @@ public class RedisInboundChannelAdapterParserTests extends RedisAvailableTests {
}
@Test
public void testAutoChannel() {
void testAutoChannel() {
assertThat(TestUtils.getPropertyValue(autoChannelAdapter, "outputChannel")).isSameAs(autoChannel);
}

View File

@@ -3,14 +3,12 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int:channel id="sendChannel"/>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,10 +18,9 @@ package org.springframework.integration.redis.config;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
@@ -33,9 +32,8 @@ import org.springframework.expression.Expression;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.handler.advice.RequestHandlerRetryAdvice;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.inbound.RedisInboundChannelAdapter;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.converter.SimpleMessageConverter;
import org.springframework.integration.test.util.TestUtils;
@@ -43,8 +41,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Oleg Zhurakousky
@@ -52,11 +49,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Artem Bilan
* @author Gunnar Hillert
* @author Gary Russell
* @author Artem Vozhdayenko
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisOutboundChannelAdapterParserTests extends RedisAvailableTests {
class RedisOutboundChannelAdapterParserTests implements RedisContainerTest {
@Autowired
private ApplicationContext context;
@@ -67,21 +64,20 @@ public class RedisOutboundChannelAdapterParserTests extends RedisAvailableTests
@Autowired
private RedisInboundChannelAdapter barInbound;
@Before
public void setup() {
@BeforeEach
void setup() {
this.fooInbound.start();
this.barInbound.start();
}
@After
public void tearDown() {
@AfterEach
void tearDown() {
this.fooInbound.stop();
this.barInbound.stop();
}
@Test
@RedisAvailable
public void validateConfiguration() {
void validateConfiguration() {
EventDrivenConsumer adapter = context.getBean("outboundAdapter", EventDrivenConsumer.class);
Object handler = context.getBean("outboundAdapter.handler");
@@ -103,10 +99,9 @@ public class RedisOutboundChannelAdapterParserTests extends RedisAvailableTests
}
@Test
@RedisAvailable
public void testOutboundChannelAdapterMessaging() throws Exception {
void testOutboundChannelAdapterMessaging() throws Exception {
MessageChannel sendChannel = context.getBean("sendChannel", MessageChannel.class);
this.awaitContainerSubscribed(TestUtils.getPropertyValue(fooInbound, "container",
RedisContainerTest.awaitContainerSubscribed(TestUtils.getPropertyValue(fooInbound, "container",
RedisMessageListenerContainer.class));
sendChannel.send(new GenericMessage<>("Hello Redis"));
QueueChannel receiveChannel = context.getBean("receiveChannel", QueueChannel.class);
@@ -122,11 +117,11 @@ public class RedisOutboundChannelAdapterParserTests extends RedisAvailableTests
assertThat(message.getPayload()).isEqualTo("Hello Redis");
}
@Test //INT-2275
@RedisAvailable
public void testOutboundChannelAdapterWithinChain() throws Exception {
@Test
//INT-2275
void testOutboundChannelAdapterWithinChain() throws Exception {
MessageChannel sendChannel = context.getBean("redisOutboundChain", MessageChannel.class);
this.awaitContainerSubscribed(TestUtils.getPropertyValue(fooInbound, "container",
RedisContainerTest.awaitContainerSubscribed(TestUtils.getPropertyValue(fooInbound, "container",
RedisMessageListenerContainer.class));
sendChannel.send(new GenericMessage<>("Hello Redis from chain"));
QueueChannel receiveChannel = context.getBean("receiveChannel", QueueChannel.class);

View File

@@ -3,14 +3,12 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int:channel id="sendChannel"/>

View File

@@ -18,10 +18,9 @@ package org.springframework.integration.redis.config;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -31,25 +30,25 @@ import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.inbound.RedisQueueInboundGateway;
import org.springframework.integration.redis.outbound.RedisQueueOutboundGateway;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author David Liu
* @author Artem Bilan
* @author Artem Vozhdayenko
*
* @since 4.1
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
class RedisQueueGatewayIntegrationTests implements RedisContainerTest {
@Value("#{redisQueue.toString().bytes}")
private byte[] queueName;
@@ -68,21 +67,22 @@ public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
@Autowired
private RedisQueueOutboundGateway outboundGateway;
@Before
public void setup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
jcf.getConnection().keyCommands().del(this.queueName);
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@BeforeEach
void setup() {
redisConnectionFactory.getConnection().keyCommands().del(this.queueName);
this.inboundGateway.start();
}
@After
public void tearDown() {
@AfterEach
void tearDown() {
this.inboundGateway.stop();
}
@Test
@RedisAvailable
public void testRequestWithReply() {
void testRequestWithReply() {
this.sendChannel.send(new GenericMessage<>(1));
Message<?> receive = this.outputChannel.receive(10000);
assertThat(receive).isNotNull();
@@ -90,8 +90,7 @@ public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testInboundGatewayStop() {
void testInboundGatewayStop() {
Integer receiveTimeout = TestUtils.getPropertyValue(this.outboundGateway, "receiveTimeout", Integer.class);
this.outboundGateway.setReceiveTimeout(1);
this.inboundGateway.stop();
@@ -99,7 +98,7 @@ public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
this.sendChannel.send(new GenericMessage<>("test1"));
}
catch (Exception e) {
assertThat(e.getMessage().contains("No reply produced")).isTrue();
assertThat(e.getMessage()).contains("No reply produced");
}
finally {
this.outboundGateway.setReceiveTimeout(receiveTimeout);
@@ -107,8 +106,7 @@ public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testNullSerializer() {
void testNullSerializer() {
Integer receiveTimeout = TestUtils.getPropertyValue(this.outboundGateway, "receiveTimeout", Integer.class);
this.outboundGateway.setReceiveTimeout(1);
this.inboundGateway.setSerializer(null);
@@ -116,7 +114,7 @@ public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
this.sendChannel.send(new GenericMessage<>("test1"));
}
catch (Exception e) {
assertThat(e.getMessage().contains("No reply produced")).isTrue();
assertThat(e.getMessage()).contains("No reply produced");
}
finally {
this.inboundGateway.setSerializer(new StringRedisSerializer());
@@ -125,8 +123,7 @@ public class RedisQueueGatewayIntegrationTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testRequestReplyWithMessage() {
void testRequestReplyWithMessage() {
this.inboundGateway.setSerializer(new JdkSerializationRedisSerializer());
this.inboundGateway.setExtractPayload(false);
this.outboundGateway.setSerializer(new JdkSerializationRedisSerializer());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,9 +17,9 @@
package org.springframework.integration.redis.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
@@ -27,23 +27,21 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.collections.RedisCollectionFactoryBean.CollectionType;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.integration.redis.inbound.RedisStoreMessageSource;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Vozhdayenko
* @since 2.2
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisStoreInboundChannelAdapterParserTests {
class RedisStoreInboundChannelAdapterParserTests {
@Autowired
private ApplicationContext context;
@@ -52,31 +50,32 @@ public class RedisStoreInboundChannelAdapterParserTests {
private RedisTemplate<?, ?> redisTemplate;
@Test
public void validateWithStringTemplate() {
void validateWithStringTemplate() {
RedisStoreMessageSource withStringTemplate =
TestUtils.getPropertyValue(context.getBean("withStringTemplate"), "source", RedisStoreMessageSource.class);
assertThat(((SpelExpression) TestUtils.getPropertyValue(withStringTemplate, "keyExpression"))
.getExpressionString()).isEqualTo("'presidents'");
assertThat(((CollectionType) TestUtils.getPropertyValue(withStringTemplate, "collectionType")).toString())
.isEqualTo("LIST");
assertThat(TestUtils.getPropertyValue(withStringTemplate, "redisTemplate") instanceof StringRedisTemplate)
.isTrue();
assertThat(TestUtils.getPropertyValue(withStringTemplate, "collectionType"))
.hasToString("LIST");
assertThat(TestUtils.getPropertyValue(withStringTemplate, "redisTemplate"))
.isInstanceOf(StringRedisTemplate.class);
}
@Test
public void validateWithExternalTemplate() {
void validateWithExternalTemplate() {
RedisStoreMessageSource withExternalTemplate =
TestUtils.getPropertyValue(context.getBean("withExternalTemplate"), "source", RedisStoreMessageSource.class);
assertThat(((SpelExpression) TestUtils.getPropertyValue(withExternalTemplate, "keyExpression"))
.getExpressionString()).isEqualTo("'presidents'");
assertThat(((CollectionType) TestUtils.getPropertyValue(withExternalTemplate, "collectionType")).toString())
.isEqualTo("LIST");
assertThat((TestUtils.getPropertyValue(withExternalTemplate, "collectionType")))
.hasToString("LIST");
assertThat(TestUtils.getPropertyValue(withExternalTemplate, "redisTemplate")).isSameAs(redisTemplate);
}
@Test(expected = BeanDefinitionParsingException.class)
public void testTemplateAndCfMutualExclusivity() {
new ClassPathXmlApplicationContext("inbound-template-cf-fail.xml", this.getClass()).close();
@Test
void testTemplateAndCfMutualExclusivity() {
assertThatThrownBy(() -> new ClassPathXmlApplicationContext("inbound-template-cf-fail.xml", this.getClass()))
.isInstanceOf(BeanDefinitionParsingException.class);
}
}

View File

@@ -3,20 +3,18 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int-redis:store-inbound-channel-adapter id="listAdapterWithSynchronizationAndRedisTemplate"
redis-template="redisTemplate"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
auto-startup="false">
redis-template="redisTemplate"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
auto-startup="false">
<int:poller fixed-rate="2000" max-messages-per-poll="10"/>
</int-redis:store-inbound-channel-adapter>

View File

@@ -24,14 +24,14 @@ import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.stream.PendingMessagesSummary;
import org.springframework.data.redis.connection.stream.ReadOffset;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
@@ -43,10 +43,8 @@ import org.springframework.integration.acks.SimpleAcknowledgment;
import org.springframework.integration.channel.FluxMessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.handler.ReactiveMessageHandlerAdapter;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.outbound.ReactiveRedisStreamMessageHandler;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableRule;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.support.RedisHeaders;
import org.springframework.integration.redis.util.Address;
import org.springframework.integration.redis.util.Person;
@@ -56,7 +54,7 @@ import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -66,12 +64,13 @@ import reactor.test.StepVerifier;
* @author Attoumane Ahamadi
* @author Artem Bilan
* @author Rohan Mukesh
* @author Artem Vozhdayenko
*
* @since 5.4
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests {
class ReactiveRedisStreamMessageProducerTests implements RedisContainerTest {
private static final String STREAM_KEY = ReactiveRedisStreamMessageProducerTests.class.getSimpleName() + ".stream";
@@ -89,19 +88,24 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
@Autowired
ReactiveMessageHandlerAdapter messageHandler;
@Before
public void delKey() {
@Autowired
ReactiveRedisStreamMessageProducer reactiveErrorRedisStreamProducer;
@Autowired
PollableChannel redisStreamErrorChannel;
@BeforeEach
void delKey() {
this.template.delete(STREAM_KEY).block();
}
@After
public void tearDown() {
@AfterEach
void tearDown() {
this.reactiveRedisStreamProducer.stop();
}
@Test
@RedisAvailable
public void testConsumerGroupCreation() {
void testConsumerGroupCreation() {
this.reactiveRedisStreamProducer.setCreateConsumerGroup(true);
this.reactiveRedisStreamProducer.setConsumerName(CONSUMER);
this.reactiveRedisStreamProducer.afterPropertiesSet();
@@ -121,8 +125,7 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
}
@Test
@RedisAvailable
public void testReadingMessageAsStandaloneClient() {
void testReadingMessageAsStandaloneClient() {
Address address = new Address("Rennes 3, France");
Person person = new Person(address, "Attoumane");
this.messageHandler.handleMessage(new GenericMessage<>(person));
@@ -149,8 +152,7 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
}
@Test
@RedisAvailable
public void testReadingMessageAsConsumerInConsumerGroup() {
void testReadingMessageAsConsumerInConsumerGroup() {
Address address = new Address("Winterfell, Westeros");
Person person = new Person(address, "John Snow");
@@ -183,8 +185,7 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
}
@Test
@RedisAvailable
public void testReadingPendingMessageWithNoAutoACK() {
void testReadingPendingMessageWithNoAutoACK() {
Address address = new Address("Winterfell, Westeros");
Person person = new Person(address, "John Snow");
@@ -230,19 +231,12 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
StepVerifier.create(pendingZeroMessage)
.assertNext(pendingMessagesSummary ->
assertThat(pendingMessagesSummary.getTotalPendingMessages()).isEqualTo(0))
assertThat(pendingMessagesSummary.getTotalPendingMessages()).isZero())
.verifyComplete();
}
@Autowired
ReactiveRedisStreamMessageProducer reactiveErrorRedisStreamProducer;
@Autowired
PollableChannel redisStreamErrorChannel;
@Test
@RedisAvailable
public void testReadingNextMessagesWhenSerializationException() {
void testReadingNextMessagesWhenSerializationException() {
Person person = new Person(new Address("Winterfell, Westeros"), "John Snow");
Date testDate = new Date();
this.reactiveErrorRedisStreamProducer.start();
@@ -282,7 +276,7 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
StepVerifier.create(pendingMessage)
.assertNext(pendingMessagesSummary ->
assertThat(pendingMessagesSummary.getTotalPendingMessages()).isEqualTo(0))
assertThat(pendingMessagesSummary.getTotalPendingMessages()).isZero())
.verifyComplete();
this.messageHandler.handleMessage(new GenericMessage<>(testDate));
@@ -296,18 +290,29 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
static class ContextConfig {
@Bean
ReactiveRedisStreamMessageHandler redisStreamMessageHandler() {
return new ReactiveRedisStreamMessageHandler(RedisAvailableRule.connectionFactory, STREAM_KEY);
ReactiveRedisConnectionFactory redisConnectionFactory() {
return RedisContainerTest.connectionFactory();
}
@Bean
public ReactiveMessageHandlerAdapter reactiveMessageHandlerAdapter() {
return new ReactiveMessageHandlerAdapter(redisStreamMessageHandler());
ReactiveRedisStreamMessageHandler redisStreamMessageHandler(
ReactiveRedisConnectionFactory redisConnectionFactory) {
return new ReactiveRedisStreamMessageHandler(redisConnectionFactory, STREAM_KEY);
}
@Bean
ReactiveRedisTemplate<String, ?> reactiveStreamOperations() {
return new ReactiveRedisTemplate<>(RedisAvailableRule.connectionFactory,
public ReactiveMessageHandlerAdapter reactiveMessageHandlerAdapter(
ReactiveRedisConnectionFactory redisConnectionFactory) {
return new ReactiveMessageHandlerAdapter(redisStreamMessageHandler(redisConnectionFactory));
}
@Bean
ReactiveRedisTemplate<String, ?> reactiveStreamOperations(
ReactiveRedisConnectionFactory redisConnectionFactory) {
return new ReactiveRedisTemplate<>(redisConnectionFactory,
RedisSerializationContext.string());
}
@@ -322,9 +327,11 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
}
@Bean
ReactiveRedisStreamMessageProducer reactiveErrorRedisStreamProducer() {
ReactiveRedisStreamMessageProducer reactiveErrorRedisStreamProducer(
ReactiveRedisConnectionFactory redisConnectionFactory) {
ReactiveRedisStreamMessageProducer messageProducer =
new ReactiveRedisStreamMessageProducer(RedisAvailableRule.connectionFactory, STREAM_KEY);
new ReactiveRedisStreamMessageProducer(redisConnectionFactory, STREAM_KEY);
messageProducer.setTargetType(Date.class);
messageProducer.setPollTimeout(Duration.ofMillis(100));
messageProducer.setCreateConsumerGroup(true);
@@ -338,9 +345,11 @@ public class ReactiveRedisStreamMessageProducerTests extends RedisAvailableTests
}
@Bean
ReactiveRedisStreamMessageProducer reactiveRedisStreamProducer() {
ReactiveRedisStreamMessageProducer reactiveRedisStreamProducer(
ReactiveRedisConnectionFactory redisConnectionFactory) {
ReactiveRedisStreamMessageProducer messageProducer =
new ReactiveRedisStreamMessageProducer(RedisAvailableRule.connectionFactory, STREAM_KEY);
new ReactiveRedisStreamMessageProducer(redisConnectionFactory, STREAM_KEY);
messageProducer.setStreamReceiverOptions(
StreamReceiver.StreamReceiverOptions.builder()
.pollTimeout(Duration.ofMillis(100))

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007-2019 the original author or authors.
* Copyright 2007-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,8 @@ package org.springframework.integration.redis.inbound;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -27,8 +28,7 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.support.RedisHeaders;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
@@ -37,14 +37,20 @@ import org.springframework.messaging.Message;
* @author Mark Fisher
* @author Artem Bilan
* @author Gary Russell
* @author Artem Vozhdayenko
*
* @since 2.1
*/
public class RedisInboundChannelAdapterTests extends RedisAvailableTests {
class RedisInboundChannelAdapterTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
public void testRedisInboundChannelAdapter() throws Exception {
void testRedisInboundChannelAdapter() throws Exception {
for (int iteration = 0; iteration < 10; iteration++) {
testRedisInboundChannelAdapterGuts(iteration);
}
@@ -55,7 +61,7 @@ public class RedisInboundChannelAdapterTests extends RedisAvailableTests {
String redisChannelName = "testRedisInboundChannelAdapterChannel";
QueueChannel channel = new QueueChannel();
RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest();
RedisConnectionFactory connectionFactory = redisConnectionFactory;
RedisInboundChannelAdapter adapter = new RedisInboundChannelAdapter(connectionFactory);
adapter.setTopics(redisChannelName);
@@ -67,7 +73,7 @@ public class RedisInboundChannelAdapterTests extends RedisAvailableTests {
StringRedisTemplate redisTemplate = new StringRedisTemplate(connectionFactory);
redisTemplate.afterPropertiesSet();
awaitFullySubscribed(TestUtils.getPropertyValue(adapter, "container", RedisMessageListenerContainer.class),
RedisContainerTest.awaitFullySubscribed(TestUtils.getPropertyValue(adapter, "container", RedisMessageListenerContainer.class),
redisTemplate, redisChannelName, channel, "foo");
for (int i = 0; i < numToTest; i++) {
@@ -82,8 +88,8 @@ public class RedisInboundChannelAdapterTests extends RedisAvailableTests {
}
assertThat(message).isNotNull();
assertThat(message.getPayload().toString()).startsWith("test-");
assertThat(message.getHeaders().get(RedisHeaders.MESSAGE_SOURCE))
.isEqualTo("testRedisInboundChannelAdapterChannel");
assertThat(message.getHeaders())
.containsEntry(RedisHeaders.MESSAGE_SOURCE, "testRedisInboundChannelAdapterChannel");
counter++;
}
assertThat(counter).isEqualTo(numToTest);
@@ -101,7 +107,7 @@ public class RedisInboundChannelAdapterTests extends RedisAvailableTests {
template.setEnableDefaultSerializer(false);
template.afterPropertiesSet();
awaitFullySubscribed(TestUtils.getPropertyValue(adapter, "container", RedisMessageListenerContainer.class),
RedisContainerTest.awaitFullySubscribed(TestUtils.getPropertyValue(adapter, "container", RedisMessageListenerContainer.class),
template, redisChannelName, channel, "foo".getBytes());
for (int i = 0; i < numToTest; i++) {

View File

@@ -9,8 +9,8 @@
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<util:constant id="TEST_QUEUE"
static-field="org.springframework.integration.redis.inbound.RedisQueueMessageDrivenEndpointTests.TEST_QUEUE"/>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2020 the original author or authors.
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,10 +30,9 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.DirectFieldAccessor;
@@ -54,9 +53,8 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.events.IntegrationEvent;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.event.RedisExceptionEvent;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
@@ -65,7 +63,7 @@ import org.springframework.messaging.MessagingException;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.ClassUtils;
/**
@@ -73,12 +71,13 @@ import org.springframework.util.ClassUtils;
* @author Artem Bilan
* @author Gary Russell
* @author Rainer Frey
* @author Artem Vozhdayenko
*
* @since 3.0
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
class RedisQueueMessageDrivenEndpointTests implements RedisContainerTest {
public static final String TEST_QUEUE = UUID.randomUUID().toString();
@@ -100,8 +99,11 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
@Autowired
private PollableChannel symmetricalOutputChannel;
@Before
public void setUpTearDown() {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@BeforeEach
void setUpTearDown() {
RedisTemplate<String, ?> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(this.connectionFactory);
redisTemplate.afterPropertiesSet();
@@ -109,9 +111,8 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
public void testInt3014Default() throws InterruptedException {
void testInt3014Default() throws InterruptedException {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(this.connectionFactory);
redisTemplate.setEnableDefaultSerializer(false);
@@ -152,9 +153,8 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
public void testInt3014ExpectMessageTrue() throws InterruptedException {
void testInt3014ExpectMessageTrue() throws InterruptedException {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(this.connectionFactory);
redisTemplate.setEnableDefaultSerializer(false);
@@ -184,13 +184,14 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
endpoint.start();
Message<Object> receive = (Message<Object>) channel.receive(10000);
assertThat(receive).isNotNull();
assertThat(receive).isEqualTo(message);
assertThat(receive)
.isNotNull()
.isEqualTo(message);
receive = (Message<Object>) errorChannel.receive(10000);
assertThat(receive).isNotNull();
assertThat(receive).isInstanceOf(ErrorMessage.class);
assertThat(receive)
.isNotNull()
.isInstanceOf(ErrorMessage.class);
assertThat(receive.getPayload()).isInstanceOf(MessagingException.class);
assertThat(((Exception) receive.getPayload()).getMessage()).contains("Deserialization of Message failed.");
assertThat(((Exception) receive.getPayload()).getCause()).isInstanceOf(ClassCastException.class);
@@ -203,8 +204,7 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testInt3017IntegrationInbound() throws InterruptedException {
void testInt3017IntegrationInbound() throws InterruptedException {
this.fromChannelEndpoint.start();
String payload = new Date().toString();
@@ -224,8 +224,7 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testInt3017IntegrationSymmetrical() throws InterruptedException {
void testInt3017IntegrationSymmetrical() throws InterruptedException {
this.symmetricalRedisChannelEndpoint.start();
UUID payload = UUID.randomUUID();
Message<UUID> message = MessageBuilder.withPayload(payload)
@@ -244,9 +243,8 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
public void testInt3442ProperlyStop() throws Exception {
void testInt3442ProperlyStop() throws Exception {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(this.connectionFactory);
redisTemplate.setEnableDefaultSerializer(false);
@@ -294,9 +292,8 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
@Test
@RedisAvailable
@Ignore("LettuceConnectionFactory doesn't support proper reinitialization after 'destroy()'")
public void testInt3196Recovery() throws Exception {
@Disabled("LettuceConnectionFactory doesn't support proper reinitialization after 'destroy()'")
void testInt3196Recovery() throws Exception {
QueueChannel channel = new QueueChannel();
final List<ApplicationEvent> exceptionEvents = new ArrayList<>();
@@ -332,7 +329,7 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
((InitializingBean) this.connectionFactory).afterPropertiesSet();
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(this.getConnectionFactoryForTest());
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setEnableDefaultSerializer(false);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
@@ -352,9 +349,8 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
public void testInt3932ReadFromLeft() throws InterruptedException {
void testInt3932ReadFromLeft() throws InterruptedException {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(this.connectionFactory);
redisTemplate.setEnableDefaultSerializer(false);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -29,8 +30,7 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.collections.RedisZSet;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.SourcePollingChannelAdapter;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.messaging.Message;
import org.springframework.messaging.SubscribableChannel;
@@ -38,16 +38,21 @@ import org.springframework.messaging.SubscribableChannel;
* @author Oleg Zhurakousky
* @author Artem Bilan
* @author Gary Russell
* @author Artem Vozhdayenko
* @since 2.2
*/
public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvailableTests {
class RedisStoreInboundChannelAdapterIntegrationTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
public void testListInboundConfiguration() throws Exception {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.prepareList(jcf);
void testListInboundConfiguration() {
RedisContainerTest.prepareList(redisConnectionFactory);
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("list-inbound-adapter.xml", this.getClass());
SourcePollingChannelAdapter spca = context.getBean("listAdapter", SourcePollingChannelAdapter.class);
@@ -62,19 +67,17 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
message = (Message<Integer>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload()).isEqualTo(Integer.valueOf(13));
this.deletePresidents(jcf);
RedisContainerTest.deletePresidents(redisConnectionFactory);
context.close();
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
// synchronization commit renames the list
public void testListInboundConfigurationWithSynchronization() throws Exception {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
StringRedisTemplate template = this.createStringRedisTemplate(jcf);
// synchronization commit renames the list
void testListInboundConfigurationWithSynchronization() throws Exception {
StringRedisTemplate template = RedisContainerTest.createStringRedisTemplate(redisConnectionFactory);
template.delete("bar");
this.prepareList(jcf);
RedisContainerTest.prepareList(redisConnectionFactory);
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("list-inbound-adapter.xml", this.getClass());
SourcePollingChannelAdapter spca =
@@ -105,13 +108,11 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
@SuppressWarnings("resource")
@Test
@RedisAvailable
// synchronization rollback renames the list
public void testListInboundConfigurationWithSynchronizationAndRollback() throws Exception {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
StringRedisTemplate template = this.createStringRedisTemplate(jcf);
// synchronization rollback renames the list
void testListInboundConfigurationWithSynchronizationAndRollback() throws Exception {
StringRedisTemplate template = RedisContainerTest.createStringRedisTemplate(redisConnectionFactory);
template.delete("baz");
this.prepareList(jcf);
RedisContainerTest.prepareList(redisConnectionFactory);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("list-inbound-adapter.xml",
this.getClass());
SubscribableChannel fail = context.getBean("redisFailChannel", SubscribableChannel.class);
@@ -137,14 +138,12 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
// synchronization commit renames the list
public void testListInboundConfigurationWithSynchronizationAndTemplate() throws Exception {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
StringRedisTemplate template = this.createStringRedisTemplate(jcf);
// synchronization commit renames the list
void testListInboundConfigurationWithSynchronizationAndTemplate() throws Exception {
StringRedisTemplate template = RedisContainerTest.createStringRedisTemplate(redisConnectionFactory);
template.delete("bar");
this.prepareList(jcf);
RedisContainerTest.prepareList(redisConnectionFactory);
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("list-inbound-adapter.xml", this.getClass());
SourcePollingChannelAdapter spca =
@@ -174,11 +173,9 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
}
@Test
@RedisAvailable
@SuppressWarnings("unchecked")
public void testZsetInboundAdapter() throws InterruptedException {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.prepareZset(jcf);
void testZsetInboundAdapter() throws InterruptedException {
RedisContainerTest.prepareZset(redisConnectionFactory);
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("zset-inbound-adapter.xml", this.getClass());
@@ -191,12 +188,12 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
Message<RedisZSet<Object>> message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().size()).isEqualTo(13);
assertThat(message.getPayload()).hasSize(13);
//poll again, should get the same stuff
message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().size()).isEqualTo(13);
assertThat(message.getPayload()).hasSize(13);
zsetAdapterNoScore.stop();
@@ -208,12 +205,12 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().rangeByScore(18, 20).size()).isEqualTo(11);
assertThat(message.getPayload().rangeByScore(18, 20)).hasSize(11);
//poll again, should get the same stuff
message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().rangeByScore(18, 20).size()).isEqualTo(11);
assertThat(message.getPayload().rangeByScore(18, 20)).hasSize(11);
zsetAdapterWithScoreRange.stop();
@@ -225,12 +222,12 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().rangeByScore(18, 18).size()).isEqualTo(2);
assertThat(message.getPayload().rangeByScore(18, 18)).hasSize(2);
//poll again, should get the same stuff
message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().rangeByScore(18, 18).size()).isEqualTo(2);
assertThat(message.getPayload().rangeByScore(18, 18)).hasSize(2);
zsetAdapterWithSingleScore.stop();
@@ -245,7 +242,7 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
zsetAdapterNoScore.start();
message = (Message<RedisZSet<Object>>) redisChannel.receive(10000);
assertThat(message).isNotNull();
assertThat(message.getPayload().size()).isEqualTo(13);
assertThat(message.getPayload()).hasSize(13);
zsetAdapterNoScore.stop();
// get only presidents for 18th century
@@ -267,7 +264,7 @@ public class RedisStoreInboundChannelAdapterIntegrationTests extends RedisAvaila
zsetAdapterNoScore.stop();
zsetAdapterWithSingleScoreAndSynchronization.stop();
this.deletePresidents(jcf);
RedisContainerTest.deletePresidents(redisConnectionFactory);
context.close();
}

View File

@@ -3,39 +3,37 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int-redis:store-inbound-channel-adapter id="listAdapter"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false"
collection-type="LIST">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false"
collection-type="LIST">
<int:poller fixed-rate="2000" max-messages-per-poll="10"/>
</int-redis:store-inbound-channel-adapter>
<int-redis:store-inbound-channel-adapter id="listAdapterWithSynchronization"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false">
<int:poller fixed-rate="2000" max-messages-per-poll="10">
<int:transactional synchronization-factory="syncFactory"/>
</int:poller>
</int-redis:store-inbound-channel-adapter>
<int-redis:store-inbound-channel-adapter id="listAdapterWithSynchronizationAndRollback"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisFailChannel"
auto-startup="false">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisFailChannel"
auto-startup="false">
<int:poller fixed-rate="2000" max-messages-per-poll="10">
<int:transactional synchronization-factory="syncFactory"/>
</int:poller>
@@ -44,12 +42,12 @@
<int:channel id="redisFailChannel"/>
<int-redis:store-inbound-channel-adapter id="listAdapterWithSynchronizationAndRedisTemplate"
redis-template="redisTemplate"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false">
redis-template="redisTemplate"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false">
<int:poller fixed-rate="2000" max-messages-per-poll="10">
<int:transactional synchronization-factory="syncFactory"/>
<int:transactional synchronization-factory="syncFactory"/>
</int:poller>
</int-redis:store-inbound-channel-adapter>
@@ -59,12 +57,12 @@
</int:transaction-synchronization-factory>
<int-redis:store-inbound-channel-adapter id="listAdapterWithSynchronizationBeforeCommit"
redis-template="redisTemplate"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false">
redis-template="redisTemplate"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false">
<int:poller fixed-rate="2000" max-messages-per-poll="10" error-channel="adapterErrors">
<int:transactional synchronization-factory="syncFactory2"/>
<int:transactional synchronization-factory="syncFactory2"/>
</int:poller>
</int-redis:store-inbound-channel-adapter>

View File

@@ -3,55 +3,53 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int-redis:store-inbound-channel-adapter id="zsetAdapterNoScore"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisChannel"
auto-startup="false"
collection-type="ZSET">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisChannel"
auto-startup="false"
collection-type="ZSET">
<int:poller fixed-rate="100"/>
</int-redis:store-inbound-channel-adapter>
<int-redis:store-inbound-channel-adapter id="zsetAdapterWithScoreRange"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisChannel"
auto-startup="false"
collection-type="ZSET">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisChannel"
auto-startup="false"
collection-type="ZSET">
<int:poller fixed-rate="100" max-messages-per-poll="2"/>
</int-redis:store-inbound-channel-adapter>
<int-redis:store-inbound-channel-adapter id="zsetAdapterWithSingleScore"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisChannel"
auto-startup="false"
collection-type="ZSET">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="redisChannel"
auto-startup="false"
collection-type="ZSET">
<int:poller fixed-rate="100"/>
</int-redis:store-inbound-channel-adapter>
<int-redis:store-inbound-channel-adapter id="zsetAdapterWithSingleScoreAndSynchronization"
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false"
collection-type="ZSET">
connection-factory="redisConnectionFactory"
key-expression="'presidents'"
channel="transformChannel"
auto-startup="false"
collection-type="ZSET">
<int:poller fixed-rate="100">
<int:transactional synchronization-factory="syncFactory"/>
</int:poller>
</int-redis:store-inbound-channel-adapter>
<int:transaction-synchronization-factory id="syncFactory">
<int:after-commit expression="payload.removeByScore(18, 18)"/>
<int:after-commit expression="payload.removeByScore(18, 18)"/>
</int:transaction-synchronization-factory>
<int:channel id="redisChannel">
@@ -59,7 +57,7 @@
</int:channel>
<int:transformer input-channel="transformChannel" output-channel="otherRedisChannel"
expression="payload.rangeByScore(18, 18).size()" />
expression="payload.rangeByScore(18, 18).size()"/>
<int:channel id="otherRedisChannel">
<int:queue/>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 the original author or authors.
* Copyright 2016-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,37 +24,39 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.leader.Context;
import org.springframework.integration.leader.DefaultCandidate;
import org.springframework.integration.leader.event.LeaderEventPublisher;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.support.leader.LockRegistryLeaderInitiator;
import org.springframework.integration.test.rule.Log4j2LevelAdjuster;
import org.springframework.integration.test.condition.LogLevels;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
/**
* @author Artem Bilan
* @author Gary Russell
* @author Glenn Renfro
* @author Artem Vozhdayenko
*
* @since 4.3.9
*/
public class RedisLockRegistryLeaderInitiatorTests extends RedisAvailableTests {
@LogLevels(categories = "org.springframework.integration.redis.leader")
class RedisLockRegistryLeaderInitiatorTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@Rule
public Log4j2LevelAdjuster adjuster =
Log4j2LevelAdjuster.trace()
.categories(true, "org.springframework.integration.redis.leader");
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
public void testDistributedLeaderElection() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), "LeaderInitiator");
void testDistributedLeaderElection() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, "LeaderInitiator");
registry.expireUnusedOlderThan(-1);
CountDownLatch granted = new CountDownLatch(1);
CountingPublisher countingPublisher = new CountingPublisher(granted);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,59 +19,59 @@ package org.springframework.integration.redis.metadata;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
/**
* @author Gunnar Hillert
* @author Artem Bilan
* @author Gary Russell
* @author Artem Vozhdayenko
* @since 3.0
*
*/
public class RedisMetadataStoreTests extends RedisAvailableTests {
class RedisMetadataStoreTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@Before
@After
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@BeforeEach
@AfterEach
public void setUpTearDown() {
this.createStringRedisTemplate(this.getConnectionFactoryForTest()).delete("testMetadata");
RedisContainerTest.createStringRedisTemplate(redisConnectionFactory).delete("testMetadata");
}
@Test
@RedisAvailable
public void testGetNonExistingKeyValue() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf);
void testGetNonExistingKeyValue() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory);
String retrievedValue = metadataStore.get("does-not-exist");
assertThat(retrievedValue).isNull();
}
@Test
@RedisAvailable
public void testPersistKeyValue() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testPersistKeyValue() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
metadataStore.put("RedisMetadataStoreTests-Spring", "Integration");
StringRedisTemplate redisTemplate = new StringRedisTemplate(jcf);
StringRedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory);
BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps("testMetadata");
assertThat(ops.get("RedisMetadataStoreTests-Spring")).isEqualTo("Integration");
}
@Test
@RedisAvailable
public void testGetValueFromMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testGetValueFromMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
metadataStore.put("RedisMetadataStoreTests-GetValue", "Hello Redis");
String retrievedValue = metadataStore.get("RedisMetadataStoreTests-GetValue");
@@ -79,23 +79,17 @@ public class RedisMetadataStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testPersistEmptyStringToMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testPersistEmptyStringToMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
metadataStore.put("RedisMetadataStoreTests-PersistEmpty", "");
String retrievedValue = metadataStore.get("RedisMetadataStoreTests-PersistEmpty");
assertThat(retrievedValue).isEqualTo("");
assertThat(retrievedValue).isEmpty();
}
@Test
@RedisAvailable
public void testPersistNullStringToMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testPersistNullStringToMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
try {
metadataStore.put("RedisMetadataStoreTests-PersistEmpty", null);
@@ -110,10 +104,8 @@ public class RedisMetadataStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testPersistWithEmptyKeyToMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testPersistWithEmptyKeyToMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
metadataStore.put("", "PersistWithEmptyKey");
String retrievedValue = metadataStore.get("");
@@ -121,10 +113,8 @@ public class RedisMetadataStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testPersistWithNullKeyToMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testPersistWithNullKeyToMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
try {
metadataStore.put(null, "something");
@@ -138,10 +128,8 @@ public class RedisMetadataStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testGetValueWithNullKeyFromMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testGetValueWithNullKeyFromMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
try {
metadataStore.get(null);
@@ -155,10 +143,8 @@ public class RedisMetadataStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testRemoveFromMetadataStore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMetadataStore metadataStore = new RedisMetadataStore(jcf, "testMetadata");
void testRemoveFromMetadataStore() {
RedisMetadataStore metadataStore = new RedisMetadataStore(redisConnectionFactory, "testMetadata");
String testKey = "RedisMetadataStoreTests-Remove";
String testValue = "Integration";

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2020 the original author or authors.
* Copyright 2020-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,40 +21,39 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.StreamOffset;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.handler.ReactiveMessageHandlerAdapter;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableRule;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.util.Address;
import org.springframework.integration.redis.util.Person;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Attoumane Ahamadi
* @author Artem Bilan
* @author Artem Vozhdayenko
*
* @since 5.4
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests {
class ReactiveRedisStreamMessageHandlerTests implements RedisContainerTest {
private static final String STREAM_KEY = ReactiveRedisStreamMessageHandlerTests.class.getSimpleName() + ".stream";
@@ -65,23 +64,25 @@ public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests
@Autowired
private ReactiveMessageHandlerAdapter handlerAdapter;
@Before
public void deleteStreamKey() {
@Autowired
private ReactiveRedisConnectionFactory redisConnectionFactory;
@BeforeEach
void deleteStreamKey() {
ReactiveRedisTemplate<String, String> template =
new ReactiveRedisTemplate<>(RedisAvailableRule.connectionFactory, RedisSerializationContext.string());
new ReactiveRedisTemplate<>(redisConnectionFactory, RedisSerializationContext.string());
template.delete(STREAM_KEY).block();
}
@Test
@RedisAvailable
public void testIntegrationStreamOutbound() {
void testIntegrationStreamOutbound() {
String messagePayload = "Hello stream message";
this.messageChannel.send(new GenericMessage<>(messagePayload));
ReactiveRedisTemplate<String, ?> template =
new ReactiveRedisTemplate<>(RedisAvailableRule.connectionFactory, RedisSerializationContext.string());
new ReactiveRedisTemplate<>(redisConnectionFactory, RedisSerializationContext.string());
ObjectRecord<String, String> record =
template.opsForStream()
@@ -94,15 +95,13 @@ public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests
}
@Test
@RedisAvailable
public void testMessageWithListPayload() {
void testMessageWithListPayload() {
List<String> messagePayload = Arrays.asList("Hello", "stream", "message");
this.handlerAdapter.handleMessage(new GenericMessage<>(messagePayload));
ReactiveRedisTemplate<String, ?> template = new ReactiveRedisTemplate<>(RedisAvailableRule.connectionFactory,
ReactiveRedisTemplate<String, ?> template = new ReactiveRedisTemplate<>(redisConnectionFactory,
RedisSerializationContext.string());
ObjectRecord<String, ?> record = template.opsForStream().read(List.class, StreamOffset
.fromStart(STREAM_KEY))
ObjectRecord<String, ?> record = template.opsForStream().read(List.class, StreamOffset.fromStart(STREAM_KEY))
.blockFirst();
assertThat(record.getStream()).isEqualTo(STREAM_KEY);
@@ -111,8 +110,7 @@ public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests
@Test
@RedisAvailable
public void testExplicitSerializationContextWithModel() {
void testExplicitSerializationContextWithModel() {
Address address = new Address("Rennes, France");
Person person = new Person(address, "Attoumane");
@@ -121,7 +119,7 @@ public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests
this.handlerAdapter.handleMessage(message);
ReactiveRedisTemplate<String, ?> template =
new ReactiveRedisTemplate<>(RedisAvailableRule.connectionFactory, RedisSerializationContext.string());
new ReactiveRedisTemplate<>(redisConnectionFactory, RedisSerializationContext.string());
ObjectRecord<String, Person> record =
template.opsForStream()
@@ -136,6 +134,11 @@ public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests
@Configuration
public static class ReactiveRedisStreamMessageHandlerTestsContext {
@Bean
ReactiveRedisConnectionFactory redisConnectionFactory() {
return RedisContainerTest.connectionFactory();
}
@Bean
public MessageChannel streamChannel(ReactiveMessageHandlerAdapter messageHandlerAdapter) {
DirectChannel directChannel = new DirectChannel();
@@ -146,9 +149,9 @@ public class ReactiveRedisStreamMessageHandlerTests extends RedisAvailableTests
@Bean
public ReactiveRedisStreamMessageHandler streamMessageHandler() {
public ReactiveRedisStreamMessageHandler streamMessageHandler(ReactiveRedisConnectionFactory redisConnectionFactory) {
return new ReactiveRedisStreamMessageHandler(RedisAvailableRule.connectionFactory, STREAM_KEY);
return new ReactiveRedisStreamMessageHandler(redisConnectionFactory, STREAM_KEY);
}
@Bean

View File

@@ -3,17 +3,15 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis
https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int:channel id="replyChannel">
<int:queue/>
@@ -34,7 +32,7 @@
<int:channel id="mgetCommandChannel"/>
<int-redis:outbound-gateway request-channel="pingChannel" reply-channel="replyChannel"
arguments-strategy=""/>
arguments-strategy=""/>
<int-redis:outbound-gateway request-channel="leftPushRightPopChannel" reply-channel="replyChannel"
connection-factory="redisConnectionFactory"

View File

@@ -22,34 +22,32 @@ import static org.assertj.core.api.Assertions.fail;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.handler.ReplyRequiredException;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.support.RedisHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Artem Bilan
* @author Gary Russell
* @author Artem Vozhdayenko
*
* @since 4.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisOutboundGatewayTests extends RedisAvailableTests {
class RedisOutboundGatewayTests implements RedisContainerTest {
@Autowired
private BeanFactory beanFactory;
@@ -75,9 +73,11 @@ public class RedisOutboundGatewayTests extends RedisAvailableTests {
@Autowired
private MessageChannel mgetCommandChannel;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Test
@RedisAvailable
public void testPingPongCommand() {
void testPingPongCommand() {
this.pingChannel.send(MessageBuilder.withPayload("foo").setHeader(RedisHeaders.COMMAND, "PING").build());
Message<?> receive = this.replyChannel.receive(1000);
assertThat(receive).isNotNull();
@@ -85,8 +85,7 @@ public class RedisOutboundGatewayTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testPushAndPopCommands() {
void testPushAndPopCommands() {
final String queueName = "si.test.testRedisOutboundGateway";
String payload = "testing";
this.leftPushRightPopChannel.send(MessageBuilder.withPayload(payload)
@@ -106,8 +105,7 @@ public class RedisOutboundGatewayTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testIncrementAtomicCommand() {
void testIncrementAtomicCommand() {
// Since 'atomicInteger' is lazy-init to avoid early Redis connection,
// we have to initialize it before send the INCR command.
this.beanFactory.getBean("atomicInteger");
@@ -120,13 +118,12 @@ public class RedisOutboundGatewayTests extends RedisAvailableTests {
receive = this.replyChannel.receive(1000);
assertThat(receive).isNotNull();
assertThat(new String((byte[]) receive.getPayload())).isEqualTo("11");
this.createStringRedisTemplate(this.getConnectionFactoryForTest()).delete("si.test.RedisAtomicInteger");
RedisContainerTest.createStringRedisTemplate(redisConnectionFactory).delete("si.test.RedisAtomicInteger");
}
@Test
@RedisAvailable
public void testGetCommand() {
this.setDelCommandChannel.send(MessageBuilder.withPayload(new String[]{ "foo", "bar" })
void testGetCommand() {
this.setDelCommandChannel.send(MessageBuilder.withPayload(new String[] {"foo", "bar"})
.setHeader(RedisHeaders.COMMAND, "SET").build());
Message<?> receive = this.replyChannel.receive(1000);
assertThat(receive).isNotNull();
@@ -153,14 +150,13 @@ public class RedisOutboundGatewayTests extends RedisAvailableTests {
@SuppressWarnings("unchecked")
@Test
@RedisAvailable
public void testMGetCommand() {
RedisConnection connection = this.getConnectionFactoryForTest().getConnection();
void testMGetCommand() {
RedisConnection connection = redisConnectionFactory.getConnection();
byte[] value1 = "bar1".getBytes();
byte[] value2 = "bar2".getBytes();
connection.stringCommands().set("foo1".getBytes(), value1);
connection.stringCommands().set("foo2".getBytes(), value2);
this.mgetCommandChannel.send(MessageBuilder.withPayload(new String[]{ "foo1", "foo2" }).build());
this.mgetCommandChannel.send(MessageBuilder.withPayload(new String[] {"foo1", "foo2"}).build());
Message<?> receive = this.replyChannel.receive(1000);
assertThat(receive).isNotNull();
assertThat((List<byte[]>) receive.getPayload()).containsExactly(value1, value2);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007-2019 the original author or authors.
* Copyright 2007-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,8 @@ import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
@@ -31,40 +32,43 @@ import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.support.MessageBuilder;
/**
* @author Mark Fisher
* @author Artem Bilan
* @author Artem Vozhdayenko
* @since 2.1
*/
public class RedisPublishingMessageHandlerTests extends RedisAvailableTests {
class RedisPublishingMessageHandlerTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
public void testRedisPublishingMessageHandler() throws Exception {
void testRedisPublishingMessageHandler() throws Exception {
int numToTest = 10;
String topic = "si.test.channel";
final CountDownLatch latch = new CountDownLatch(numToTest * 2);
RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest();
MessageListenerAdapter listener = new MessageListenerAdapter();
listener.setDelegate(new Listener(latch));
listener.setSerializer(new StringRedisSerializer());
listener.afterPropertiesSet();
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setConnectionFactory(redisConnectionFactory);
container.afterPropertiesSet();
container.addMessageListener(listener, Collections.<Topic>singletonList(new ChannelTopic(topic)));
container.start();
this.awaitContainerSubscribed(container);
RedisContainerTest.awaitContainerSubscribed(container);
final RedisPublishingMessageHandler handler = new RedisPublishingMessageHandler(connectionFactory);
final RedisPublishingMessageHandler handler = new RedisPublishingMessageHandler(redisConnectionFactory);
handler.setTopicExpression(new LiteralExpression(topic));
for (int i = 0; i < numToTest; i++) {

View File

@@ -3,14 +3,12 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int:chain input-channel="toRedisQueueChannel">
<int-redis:queue-outbound-channel-adapter queue-expression="payload"

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,7 @@ import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -34,8 +33,7 @@ import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.mapping.InboundMessageMapper;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.json.Jackson2JsonMessageParser;
import org.springframework.integration.support.json.JsonInboundMessageMapper;
@@ -43,20 +41,19 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Gunnar Hillert
* @author Artem Bilan
* @author Rainer Frey
* @author Artem Vozhdayenko
*
* @since 3.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
class RedisQueueOutboundChannelAdapterTests implements RedisContainerTest {
@Autowired
private RedisConnectionFactory connectionFactory;
@@ -67,8 +64,7 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
@Test
@RedisAvailable
public void testInt3015Default() throws Exception {
void testInt3015Default() {
final String queueName = "si.test.testRedisQueueOutboundChannelAdapter";
@@ -83,9 +79,9 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
redisTemplate.afterPropertiesSet();
Object result = redisTemplate.boundListOps(queueName).rightPop(5000, TimeUnit.MILLISECONDS);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(payload);
assertThat(result)
.isNotNull()
.isEqualTo(payload);
Date payload2 = new Date();
handler.handleMessage(MessageBuilder.withPayload(payload2).build());
@@ -98,14 +94,13 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
redisTemplate2.afterPropertiesSet();
Object result2 = redisTemplate2.boundListOps(queueName).rightPop(5000, TimeUnit.MILLISECONDS);
assertThat(result2).isNotNull();
assertThat(result2).isEqualTo(payload2);
assertThat(result2)
.isNotNull()
.isEqualTo(payload2);
}
@Test
@RedisAvailable
public void testInt3015ExtractPayloadFalse() throws Exception {
void testInt3015ExtractPayloadFalse() {
final String queueName = "si.test.testRedisQueueOutboundChannelAdapter2";
@@ -124,15 +119,14 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
redisTemplate.afterPropertiesSet();
Object result = redisTemplate.boundListOps(queueName).rightPop(5000, TimeUnit.MILLISECONDS);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(message);
assertThat(result)
.isNotNull()
.isEqualTo(message);
}
@Test
@RedisAvailable
public void testInt3015ExplicitSerializer() throws Exception {
void testInt3015ExplicitSerializer() {
final String queueName = "si.test.testRedisQueueOutboundChannelAdapter2";
@@ -147,21 +141,20 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
handler.handleMessage(new GenericMessage<Object>(Arrays.asList("foo", "bar", "baz")));
Object result = redisTemplate.boundListOps(queueName).rightPop(5000, TimeUnit.MILLISECONDS);
assertThat(result).isNotNull();
assertThat(result).isEqualTo("[\"foo\",\"bar\",\"baz\"]");
assertThat(result)
.isNotNull()
.isEqualTo("[\"foo\",\"bar\",\"baz\"]");
handler.handleMessage(new GenericMessage<Object>("test"));
result = redisTemplate.boundListOps(queueName).rightPop(5000, TimeUnit.MILLISECONDS);
assertThat(result).isNotNull();
assertThat(result).isEqualTo("\"test\"");
assertThat(result)
.isNotNull()
.isEqualTo("\"test\"");
}
@Test
@RedisAvailable
public void testInt3017IntegrationOutbound() throws Exception {
void testInt3017IntegrationOutbound() {
final String queueName = "si.test.Int3017IntegrationOutbound";
@@ -181,8 +174,7 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testInt3932LeftPushFalse() throws Exception {
void testInt3932LeftPushFalse() {
final String queueName = "si.test.Int3932LeftPushFalse";
@@ -201,9 +193,9 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
redisTemplate.afterPropertiesSet();
Object result = redisTemplate.boundListOps(queueName).leftPop(5000, TimeUnit.MILLISECONDS);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(payload);
assertThat(result)
.isNotNull()
.isEqualTo(payload);
RedisTemplate<String, ?> redisTemplate2 = new RedisTemplate<String, Object>();
redisTemplate2.setConnectionFactory(this.connectionFactory);
@@ -213,9 +205,9 @@ public class RedisQueueOutboundChannelAdapterTests extends RedisAvailableTests {
redisTemplate2.afterPropertiesSet();
Object result2 = redisTemplate2.boundListOps(queueName).leftPop(5000, TimeUnit.MILLISECONDS);
assertThat(result2).isNotNull();
assertThat(result2).isEqualTo(payload2);
assertThat(result2)
.isNotNull()
.isEqualTo(payload2);
}
}

View File

@@ -3,14 +3,12 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-redis="http://www.springframework.org/schema/integration/redis"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration/redis https://www.springframework.org/schema/integration/redis/spring-integration-redis.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int:channel id="someChannel"/>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007-2019 the original author or authors.
* Copyright 2007-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.integration.redis.outbound;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.HashMap;
@@ -26,10 +27,9 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -49,8 +49,7 @@ import org.springframework.data.redis.support.collections.RedisSet;
import org.springframework.data.redis.support.collections.RedisZSet;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.support.RedisHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.TestUtils;
@@ -58,21 +57,20 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
* @author Artem Vozhdayenko
*
* @since 2.2
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvailableTests {
class RedisStoreOutboundChannelAdapterIntegrationTests implements RedisContainerTest {
private final StringRedisTemplate redisTemplate = new StringRedisTemplate();
@@ -127,11 +125,13 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
@Qualifier("simpleProperty")
private MessageChannel simplePropertyChannel;
@Before
@After
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@BeforeEach
@AfterEach
public void setup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
this.redisTemplate.setConnectionFactory(jcf);
this.redisTemplate.setConnectionFactory(redisConnectionFactory);
this.redisTemplate.afterPropertiesSet();
this.redisTemplate.delete("pepboys");
@@ -141,10 +141,9 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
}
@Test
@RedisAvailable
public void testListWithKeyAsHeader() {
void testListWithKeyAsHeader() {
RedisList<String> redisList = new DefaultRedisList<String>("pepboys", this.redisTemplate);
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
List<String> pepboys = new ArrayList<String>();
pepboys.add("Manny");
@@ -153,27 +152,25 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<List<String>> message = MessageBuilder.withPayload(pepboys).setHeader(RedisHeaders.KEY, "pepboys").build();
this.listWithKeyAsHeaderChannel.send(message);
assertThat(redisList.size()).isEqualTo(3);
assertThat(redisList).hasSize(3);
}
@Test
@RedisAvailable
public void testListWithKeyAsHeaderSimple() {
void testListWithKeyAsHeaderSimple() {
redisTemplate.delete("foo");
RedisList<String> redisList = new DefaultRedisList<String>("foo", this.redisTemplate);
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
Message<String> message = MessageBuilder.withPayload("bar").setHeader("redis_key", "foo").build();
this.listWithKeyAsHeaderChannel.send(message);
assertThat(redisList.size()).isEqualTo(1);
assertThat(redisList).hasSize(1);
}
@Test
@RedisAvailable
public void testListWithProvidedKey() {
void testListWithProvidedKey() {
RedisList<String> redisList = new DefaultRedisList<String>("pepboys", this.redisTemplate);
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
List<String> pepboys = new ArrayList<String>();
pepboys.add("Manny");
@@ -182,14 +179,13 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<List<String>> message = MessageBuilder.withPayload(pepboys).build();
this.listWithKeyProvidedChannel.send(message);
assertThat(redisList.size()).isEqualTo(3);
assertThat(redisList).hasSize(3);
}
@Test
@RedisAvailable
public void testZsetSimplePayloadIncrement() {
void testZsetSimplePayloadIncrement() {
RedisZSet<String> redisZSet = new DefaultRedisZSet<String>("foo", this.redisTemplate);
assertThat(redisZSet.size()).isEqualTo(0);
assertThat(redisZSet).isEmpty();
Message<String> message = MessageBuilder.withPayload("bar")
.setHeader(RedisHeaders.KEY, "foo")
@@ -197,40 +193,38 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
.build();
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(1));
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(2));
}
@Test
@RedisAvailable
public void testZsetSimplePayloadOverwrite() {
void testZsetSimplePayloadOverwrite() {
RedisZSet<String> redisZSet = new DefaultRedisZSet<String>("foo", this.redisTemplate);
assertThat(redisZSet.size()).isEqualTo(0);
assertThat(redisZSet).isEmpty();
Message<String> message = MessageBuilder.withPayload("bar")
.setHeader(RedisHeaders.KEY, "foo")
.build();
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(1));
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(1));
}
@Test
@RedisAvailable
public void testZsetSimplePayloadIncrementBy2() {
void testZsetSimplePayloadIncrementBy2() {
RedisZSet<String> redisZSet = new DefaultRedisZSet<String>("foo", this.redisTemplate);
assertThat(redisZSet.size()).isEqualTo(0);
assertThat(redisZSet).isEmpty();
Message<String> message = MessageBuilder.withPayload("bar")
.setHeader(RedisHeaders.KEY, "foo")
@@ -239,20 +233,19 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
.build();
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(2));
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(4));
}
@Test
@RedisAvailable
public void testZsetSimplePayloadOverwriteWithHeaderScore() {
void testZsetSimplePayloadOverwriteWithHeaderScore() {
RedisZSet<String> redisZSet = new DefaultRedisZSet<String>("foo", this.redisTemplate);
assertThat(redisZSet.size()).isEqualTo(0);
assertThat(redisZSet).isEmpty();
Message<String> message = MessageBuilder.withPayload("bar")
.setHeader(RedisHeaders.KEY, "foo")
@@ -261,20 +254,19 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
.build();
this.zsetChannel.send(message);
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(2));
this.zsetChannel.send(MessageBuilder.fromMessage(message).setHeader(RedisHeaders.ZSET_SCORE, 15).build());
assertThat(redisZSet.size()).isEqualTo(1);
assertThat(redisZSet).hasSize(1);
assertThat(redisZSet.score("bar")).isEqualTo(Double.valueOf(15));
}
@Test
@RedisAvailable
public void testMapToZsetWithProvidedKey() {
void testMapToZsetWithProvidedKey() {
RedisZSet<String> redisZset = new DefaultRedisZSet<String>("presidents", this.redisTemplate);
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
Map<String, Integer> presidents = new HashMap<String, Integer>();
presidents.put("John Adams", 18);
@@ -290,10 +282,10 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
this.mapToZsetChannel.send(message);
assertThat(redisZset.size()).isEqualTo(5);
assertThat(redisZset.rangeByScore(18, 18).size()).isEqualTo(1);
assertThat(redisZset.rangeByScore(18, 19).size()).isEqualTo(4);
assertThat(redisZset.rangeByScore(21, 21).size()).isEqualTo(1);
assertThat(redisZset).hasSize(5);
assertThat(redisZset.rangeByScore(18, 18)).hasSize(1);
assertThat(redisZset.rangeByScore(18, 19)).hasSize(4);
assertThat(redisZset.rangeByScore(21, 21)).hasSize(1);
RedisStoreWritingMessageHandler handler =
this.beanFactory.getBean("mapToZset.handler", RedisStoreWritingMessageHandler.class);
@@ -301,10 +293,10 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
this.mapToZsetChannel.send(message);
assertThat(redisZset.size()).isEqualTo(5);
assertThat(redisZset.rangeByScore(36, 36).size()).isEqualTo(1);
assertThat(redisZset.rangeByScore(36, 38).size()).isEqualTo(4);
assertThat(redisZset.rangeByScore(42, 42).size()).isEqualTo(1);
assertThat(redisZset).hasSize(5);
assertThat(redisZset.rangeByScore(36, 36)).hasSize(1);
assertThat(redisZset.rangeByScore(36, 38)).hasSize(4);
assertThat(redisZset.rangeByScore(42, 42)).hasSize(1);
// test overwrite score behavior
presidents.put("Barack Obama", 31);
@@ -313,18 +305,17 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
.setHeader(RedisHeaders.ZSET_INCREMENT_SCORE, false)
.build());
assertThat(redisZset.size()).isEqualTo(5);
assertThat(redisZset.rangeByScore(18, 18).size()).isEqualTo(1);
assertThat(redisZset.rangeByScore(18, 19).size()).isEqualTo(4);
assertThat(redisZset.rangeByScore(31, 31).size()).isEqualTo(1);
assertThat(redisZset).hasSize(5);
assertThat(redisZset.rangeByScore(18, 18)).hasSize(1);
assertThat(redisZset.rangeByScore(18, 19)).hasSize(4);
assertThat(redisZset.rangeByScore(31, 31)).hasSize(1);
}
@Test
@RedisAvailable
public void testMapToMapWithProvidedKey() {
void testMapToMapWithProvidedKey() {
RedisMap<String, String> redisMap = new DefaultRedisMap<String, String>("pepboys", this.redisTemplate);
assertThat(redisMap.size()).isEqualTo(0);
assertThat(redisMap).isEmpty();
Map<String, String> pepboys = new HashMap<String, String>();
pepboys.put("1", "Manny");
@@ -333,9 +324,10 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<Map<String, String>> message = MessageBuilder.withPayload(pepboys).build();
this.mapToMapAChannel.send(message);
assertThat(redisMap.get("1")).isEqualTo("Manny");
assertThat(redisMap.get("2")).isEqualTo("Moe");
assertThat(redisMap.get("3")).isEqualTo("Jack");
assertThat(redisMap)
.containsEntry("1", "Manny")
.containsEntry("2", "Moe")
.containsEntry("3", "Jack");
RedisStoreWritingMessageHandler handler = this.beanFactory.getBean("mapToMapA.handler",
RedisStoreWritingMessageHandler.class);
@@ -345,13 +337,13 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
.isEqualTo("'foo'");
}
@Test(expected = MessageHandlingException.class) // map key is not provided
@RedisAvailable
public void testMapToMapAsSingleEntryWithKeyAsHeaderFail() {
@Test
// map key is not provided
void testMapToMapAsSingleEntryWithKeyAsHeaderFail() {
RedisMap<String, Map<String, String>> redisMap =
new DefaultRedisMap<String, Map<String, String>>("pepboys", this.redisTemplate);
assertThat(redisMap.size()).isEqualTo(0);
assertThat(redisMap).isEmpty();
Map<String, String> pepboys = new HashMap<String, String>();
pepboys.put("1", "Manny");
@@ -361,22 +353,23 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<Map<String, String>> message = MessageBuilder.withPayload(pepboys).
setHeader(RedisHeaders.KEY, "pepboys").build();
this.mapToMapBChannel.send(message);
assertThatThrownBy(() -> this.mapToMapBChannel.send(message))
.isInstanceOf(MessageHandlingException.class);
}
@Test(expected = MessageHandlingException.class) // key is not provided
@RedisAvailable
public void testMapToMapNoKey() {
@Test
// key is not provided
void testMapToMapNoKey() {
RedisTemplate<String, Map<String, Map<String, String>>> redisTemplate = new RedisTemplate<String, Map<String, Map<String, String>>>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(getConnectionFactoryForTest());
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
RedisMap<String, Map<String, String>> redisMap =
new DefaultRedisMap<String, Map<String, String>>("pepboys", redisTemplate);
assertThat(redisMap.size()).isEqualTo(0);
assertThat(redisMap).isEmpty();
Map<String, String> pepboys = new HashMap<String, String>();
pepboys.put("1", "Manny");
@@ -384,22 +377,22 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
pepboys.put("3", "Jack");
Message<Map<String, String>> message = MessageBuilder.withPayload(pepboys).build();
this.mapToMapBChannel.send(message);
assertThatThrownBy(() -> this.mapToMapBChannel.send(message))
.isInstanceOf(MessageHandlingException.class);
}
@Test
@RedisAvailable
public void testMapToMapAsSingleEntryWithKeyAsHeader() {
void testMapToMapAsSingleEntryWithKeyAsHeader() {
RedisTemplate<String, Map<String, Map<String, String>>> redisTemplate = new RedisTemplate<String, Map<String, Map<String, String>>>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(getConnectionFactoryForTest());
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
RedisMap<String, Map<String, String>> redisMap =
new DefaultRedisMap<String, Map<String, String>>("pepboys", redisTemplate);
assertThat(redisMap.size()).isEqualTo(0);
assertThat(redisMap).isEmpty();
Map<String, String> pepboys = new HashMap<String, String>();
pepboys.put("1", "Manny");
@@ -411,17 +404,17 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
this.mapToMapBChannel.send(message);
Map<String, String> pepboyz = redisMap.get("foo");
assertThat(pepboyz.get("1")).isEqualTo("Manny");
assertThat(pepboyz.get("2")).isEqualTo("Moe");
assertThat(pepboyz.get("3")).isEqualTo("Jack");
assertThat(pepboyz)
.containsEntry("1", "Manny")
.containsEntry("2", "Moe")
.containsEntry("3", "Jack");
}
@Test
@RedisAvailable
public void testStoreSimpleStringInMap() {
void testStoreSimpleStringInMap() {
RedisMap<String, String> redisMap = new DefaultRedisMap<String, String>("bar", this.redisTemplate);
assertThat(redisMap.size()).isEqualTo(0);
assertThat(redisMap).isEmpty();
Message<String> message = MessageBuilder.withPayload("hello, world!").
setHeader(RedisHeaders.KEY, "bar").setHeader(RedisHeaders.MAP_KEY, "foo").build();
@@ -433,10 +426,9 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
}
@Test
@RedisAvailable
public void testSetWithKeyAsHeader() {
void testSetWithKeyAsHeader() {
RedisSet<String> redisSet = new DefaultRedisSet<String>("pepboys", this.redisTemplate);
assertThat(redisSet.size()).isEqualTo(0);
assertThat(redisSet).isEmpty();
Set<String> pepboys = new HashSet<String>();
pepboys.add("Manny");
@@ -445,27 +437,25 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<Set<String>> message = MessageBuilder.withPayload(pepboys).setHeader("redis_key", "pepboys").build();
this.setChannel.send(message);
assertThat(redisSet.size()).isEqualTo(3);
assertThat(redisSet).hasSize(3);
}
@Test
@RedisAvailable
public void testSetWithKeyAsHeaderSimple() {
void testSetWithKeyAsHeaderSimple() {
RedisSet<String> redisSet = new DefaultRedisSet<String>("foo", this.redisTemplate);
assertThat(redisSet.size()).isEqualTo(0);
assertThat(redisSet).isEmpty();
Message<String> message = MessageBuilder.withPayload("foo")
.setHeader(RedisHeaders.KEY, "foo").build();
this.setChannel.send(message);
assertThat(redisSet.size()).isEqualTo(1);
assertThat(redisSet).hasSize(1);
}
@Test
@RedisAvailable
public void testSetWithKeyAsHeaderNotParsed() {
void testSetWithKeyAsHeaderNotParsed() {
RedisSet<String> redisSet = new DefaultRedisSet<String>("pepboys", this.redisTemplate);
assertThat(redisSet.size()).isEqualTo(0);
assertThat(redisSet).isEmpty();
Set<String> pepboys = new HashSet<String>();
pepboys.add("Manny");
@@ -474,28 +464,26 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<Set<String>> message = MessageBuilder.withPayload(pepboys).setHeader("redis_key", "pepboys").build();
this.setNotParsedChannel.send(message);
assertThat(redisSet.size()).isEqualTo(1);
assertThat(redisSet).hasSize(1);
}
@Test
@RedisAvailable
public void testPojoIntoSet() {
void testPojoIntoSet() {
RedisSet<String> redisSet = new DefaultRedisSet<String>("pepboys", this.redisTemplate);
assertThat(redisSet.size()).isEqualTo(0);
assertThat(redisSet).isEmpty();
String pepboy = "Manny";
Message<String> message = MessageBuilder.withPayload(pepboy).setHeader("redis_key", "pepboys").build();
this.pojoIntoSetChannel.send(message);
assertThat(redisSet.size()).isEqualTo(1);
assertThat(redisSet).hasSize(1);
}
@Test
@RedisAvailable
public void testProperties() {
void testProperties() {
RedisProperties redisProperties = new RedisProperties("pepboys", this.redisTemplate);
assertThat(redisProperties.size()).isEqualTo(0);
assertThat(redisProperties).isEmpty();
Properties pepboys = new Properties();
pepboys.put("1", "Manny");
@@ -505,17 +493,17 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
Message<Properties> message = MessageBuilder.withPayload(pepboys).build();
this.propertyChannel.send(message);
assertThat(redisProperties.get("1")).isEqualTo("Manny");
assertThat(redisProperties.get("2")).isEqualTo("Moe");
assertThat(redisProperties.get("3")).isEqualTo("Jack");
assertThat(redisProperties)
.containsEntry("1", "Manny")
.containsEntry("2", "Moe")
.containsEntry("3", "Jack");
}
@Test
@RedisAvailable
public void testPropertiesSimple() {
void testPropertiesSimple() {
RedisProperties redisProperties = new RedisProperties("foo", this.redisTemplate);
assertThat(redisProperties.size()).isEqualTo(0);
assertThat(redisProperties).isEmpty();
Message<String> message = MessageBuilder.withPayload("bar")
.setHeader(RedisHeaders.KEY, "foo")
@@ -523,7 +511,7 @@ public class RedisStoreOutboundChannelAdapterIntegrationTests extends RedisAvail
.build();
this.simplePropertyChannel.send(message);
assertThat(redisProperties.get("qux")).isEqualTo("bar");
assertThat(redisProperties).containsEntry("qux", "bar");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.integration.redis.outbound;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
@@ -27,7 +28,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -41,8 +43,7 @@ import org.springframework.data.redis.support.collections.RedisCollectionFactory
import org.springframework.data.redis.support.collections.RedisList;
import org.springframework.data.redis.support.collections.RedisZSet;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.support.RedisHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
@@ -55,108 +56,108 @@ import org.springframework.messaging.support.GenericMessage;
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
* @author Artem Vozhdayenko
*/
public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
class RedisStoreWritingMessageHandlerTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Test
@RedisAvailable
public void testListWithListPayloadParsedAndProvidedKey() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testListWithListPayloadParsedAndProvidedKey() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisList<String> redisList =
new DefaultRedisList<String>(key, this.initTemplate(jcf, new StringRedisTemplate()));
new DefaultRedisList<>(key, this.initTemplate(redisConnectionFactory, new StringRedisTemplate()));
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
Message<List<String>> message = new GenericMessage<List<String>>(list);
Message<List<String>> message = new GenericMessage<>(list);
handler.handleMessage(message);
assertThat(redisList.size()).isEqualTo(3);
assertThat(redisList).hasSize(3);
assertThat(redisList.get(0)).isEqualTo("Manny");
assertThat(redisList.get(1)).isEqualTo("Moe");
assertThat(redisList.get(2)).isEqualTo("Jack");
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testListWithListPayloadParsedAndProvidedKeyAsHeader() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testListWithListPayloadParsedAndProvidedKeyAsHeader() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisList<String> redisList =
new DefaultRedisList<String>(key, this.initTemplate(jcf, new StringRedisTemplate()));
new DefaultRedisList<>(key, this.initTemplate(redisConnectionFactory, new StringRedisTemplate()));
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
Message<List<String>> message = MessageBuilder.withPayload(list).setHeader("redis_key", key).build();
handler.handleMessage(message);
assertThat(redisList.size()).isEqualTo(3);
assertThat(redisList).hasSize(3);
assertThat(redisList.get(0)).isEqualTo("Manny");
assertThat(redisList.get(1)).isEqualTo("Moe");
assertThat(redisList.get(2)).isEqualTo("Jack");
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@RedisAvailable
@Test(expected = MessageHandlingException.class)
public void testListWithListPayloadParsedAndNoKey() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
@Test
void testListWithListPayloadParsedAndNoKey() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisList<String> redisList =
new DefaultRedisList<String>(key, this.initTemplate(jcf, new RedisTemplate<String, String>()));
new DefaultRedisList<>(key, this.initTemplate(redisConnectionFactory, new RedisTemplate<>()));
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
Message<List<String>> message = MessageBuilder.withPayload(list).build();
handler.handleMessage(message);
this.deleteKey(jcf, "foo");
assertThatThrownBy(() -> handler.handleMessage(message)).isInstanceOf(MessageHandlingException.class);
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testListWithListPayloadAsSingleEntry() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testListWithListPayloadAsSingleEntry() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisList<List<String>> redisList =
new DefaultRedisList<List<String>>(key, this.initTemplate(jcf, new RedisTemplate<String, List<String>>()));
new DefaultRedisList<>(key, this.initTemplate(redisConnectionFactory, new RedisTemplate<>()));
assertThat(redisList.size()).isEqualTo(0);
assertThat(redisList).isEmpty();
RedisTemplate<String, List<String>> template = this.initTemplate(jcf, new RedisTemplate<String, List<String>>());
RedisTemplate<String, List<String>> template = this.initTemplate(redisConnectionFactory, new RedisTemplate<>());
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(template);
handler.setKey(key);
@@ -164,40 +165,38 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
Message<List<String>> message = new GenericMessage<List<String>>(list);
Message<List<String>> message = new GenericMessage<>(list);
handler.handleMessage(message);
assertThat(redisList.size()).isEqualTo(1);
assertThat(redisList).hasSize(1);
List<String> resultList = redisList.get(0);
assertThat(resultList.get(0)).isEqualTo("Manny");
assertThat(resultList.get(1)).isEqualTo("Moe");
assertThat(resultList.get(2)).isEqualTo("Jack");
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testZsetWithListPayloadParsedAndProvidedKeyDefault() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testZsetWithListPayloadParsedAndProvidedKeyDefault() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisZSet<String> redisZset =
new DefaultRedisZSet<String>(key, this.initTemplate(jcf, new StringRedisTemplate()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new StringRedisTemplate()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.ZSET);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
@@ -206,41 +205,39 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
.build();
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(3);
assertThat(redisZset).hasSize(3);
Set<TypedTuple<String>> pepboys = redisZset.rangeByScoreWithScores(1, 1);
for (TypedTuple<String> pepboy : pepboys) {
assertThat(pepboy.getScore() == 1).isTrue();
assertThat(pepboy.getScore()).isEqualTo(1);
}
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(3);
assertThat(redisZset).hasSize(3);
pepboys = redisZset.rangeByScoreWithScores(1, 2);
// should have incremented by 1
for (TypedTuple<String> pepboy : pepboys) {
assertThat(pepboy.getScore()).isEqualTo(Double.valueOf(2));
}
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testZsetWithListPayloadParsedAndProvidedKeyScoreIncrement() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testZsetWithListPayloadParsedAndProvidedKeyScoreIncrement() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisZSet<String> redisZset =
new DefaultRedisZSet<String>(key, this.initTemplate(jcf, new StringRedisTemplate()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new StringRedisTemplate()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.ZSET);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
@@ -250,41 +247,39 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(3);
assertThat(redisZset).hasSize(3);
Set<TypedTuple<String>> pepboys = redisZset.rangeByScoreWithScores(1, 1);
for (TypedTuple<String> pepboy : pepboys) {
assertThat(pepboy.getScore() == 1).isTrue();
assertThat(pepboy.getScore()).isEqualTo(1);
}
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(3);
assertThat(redisZset).hasSize(3);
pepboys = redisZset.rangeByScoreWithScores(1, 2);
// should have incremented
for (TypedTuple<String> pepboy : pepboys) {
assertThat(pepboy.getScore() == 2).isTrue();
assertThat(pepboy.getScore()).isEqualTo(2);
}
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testZsetWithListPayloadParsedAndProvidedKeyScoreIncrementAsStringHeader() { // see INT-2775
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testZsetWithListPayloadParsedAndProvidedKeyScoreIncrementAsStringHeader() { // see INT-2775
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisZSet<String> redisZset =
new DefaultRedisZSet<String>(key, this.initTemplate(jcf, new StringRedisTemplate()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new StringRedisTemplate()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.ZSET);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
@@ -294,34 +289,32 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(3);
assertThat(redisZset).hasSize(3);
Set<TypedTuple<String>> pepboys = redisZset.rangeByScoreWithScores(1, 1);
for (TypedTuple<String> pepboy : pepboys) {
assertThat(pepboy.getScore() == 1).isTrue();
assertThat(pepboy.getScore()).isEqualTo(1);
}
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(3);
assertThat(redisZset).hasSize(3);
pepboys = redisZset.rangeByScoreWithScores(1, 2);
// should have incremented
for (TypedTuple<String> pepboy : pepboys) {
assertThat(pepboy.getScore() == 2).isTrue();
assertThat(pepboy.getScore()).isEqualTo(2);
}
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testZsetWithListPayloadAsSingleEntryAndHeaderKeyHeaderScore() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testZsetWithListPayloadAsSingleEntryAndHeaderKeyHeaderScore() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisZSet<List<String>> redisZset =
new DefaultRedisZSet<List<String>>(key, this.initTemplate(jcf, new RedisTemplate<String, List<String>>()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new RedisTemplate<>()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisTemplate<String, List<String>> template = this.initTemplate(jcf, new RedisTemplate<String, List<String>>());
RedisTemplate<String, List<String>> template = this.initTemplate(redisConnectionFactory, new RedisTemplate<>());
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(template);
@@ -330,41 +323,39 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
list.add("Manny");
list.add("Moe");
list.add("Jack");
Message<List<String>> message = MessageBuilder.withPayload(list).setHeader("redis_key", key).
setHeader("redis_zsetScore", 4).build();
setHeader("redis_zsetScore", 4).build();
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(1);
assertThat(redisZset).hasSize(1);
Set<TypedTuple<List<String>>> entries = redisZset.rangeByScoreWithScores(1, 4);
for (TypedTuple<List<String>> pepboys : entries) {
assertThat(pepboys.getScore() == 4).isTrue();
assertThat(pepboys.getScore()).isEqualTo(4);
}
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testZsetWithMapPayloadParsedHeaderKey() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deletePresidents(jcf);
void testZsetWithMapPayloadParsedHeaderKey() {
RedisContainerTest.deletePresidents(redisConnectionFactory);
String key = "presidents";
RedisZSet<String> redisZset =
new DefaultRedisZSet<String>(key, this.initTemplate(jcf, new StringRedisTemplate()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new StringRedisTemplate()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.ZSET);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
Map<String, Double> presidents = new HashMap<String, Double>();
Map<String, Double> presidents = new HashMap<>();
presidents.put("John Adams", 18D);
presidents.put("Barack Obama", 21D);
@@ -384,25 +375,23 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
Message<Map<String, Double>> message = MessageBuilder.withPayload(presidents).setHeader("redis_key", key).build();
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(13);
assertThat(redisZset).hasSize(13);
Set<TypedTuple<String>> entries = redisZset.rangeByScoreWithScores(18, 19);
assertThat(entries.size()).isEqualTo(6);
this.deletePresidents(jcf);
assertThat(entries).hasSize(6);
RedisContainerTest.deletePresidents(redisConnectionFactory);
}
@Test
@RedisAvailable
public void testZsetWithMapPayloadPojoParsedHeaderKey() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deletePresidents(jcf);
void testZsetWithMapPayloadPojoParsedHeaderKey() {
RedisContainerTest.deletePresidents(redisConnectionFactory);
String key = "presidents";
RedisZSet<President> redisZset =
new DefaultRedisZSet<President>(key, this.initTemplate(jcf, new RedisTemplate<String, President>()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new RedisTemplate<>()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisTemplate<String, President> template = this.initTemplate(jcf, new RedisTemplate<String, President>());
RedisTemplate<String, President> template = this.initTemplate(redisConnectionFactory, new RedisTemplate<>());
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(template);
handler.setKey(key);
@@ -410,7 +399,7 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
Map<President, Double> presidents = new HashMap<President, Double>();
Map<President, Double> presidents = new HashMap<>();
presidents.put(new President("John Adams"), 18D);
presidents.put(new President("Barack Obama"), 21D);
@@ -430,25 +419,23 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
Message<Map<President, Double>> message = MessageBuilder.withPayload(presidents).setHeader("redis_key", key).build();
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(13);
assertThat(redisZset).hasSize(13);
Set<TypedTuple<President>> entries = redisZset.rangeByScoreWithScores(18, 19);
assertThat(entries.size()).isEqualTo(6);
this.deletePresidents(jcf);
assertThat(entries).hasSize(6);
RedisContainerTest.deletePresidents(redisConnectionFactory);
}
@Test
@RedisAvailable
public void testZsetWithMapPayloadPojoAsSingleEntryHeaderKey() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deletePresidents(jcf);
void testZsetWithMapPayloadPojoAsSingleEntryHeaderKey() {
RedisContainerTest.deletePresidents(redisConnectionFactory);
String key = "presidents";
RedisZSet<Map<President, Double>> redisZset =
new DefaultRedisZSet<Map<President, Double>>(key, this.initTemplate(jcf, new RedisTemplate<String, Map<President, Double>>()));
new DefaultRedisZSet<>(key, this.initTemplate(redisConnectionFactory, new RedisTemplate<>()));
assertThat(redisZset.size()).isEqualTo(0);
assertThat(redisZset).isEmpty();
RedisTemplate<String, Map<President, Double>> template = this.initTemplate(jcf, new RedisTemplate<String, Map<President, Double>>());
RedisTemplate<String, Map<President, Double>> template = this.initTemplate(redisConnectionFactory, new RedisTemplate<>());
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(template);
handler.setKey(key);
@@ -457,7 +444,7 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
Map<President, Double> presidents = new HashMap<President, Double>();
Map<President, Double> presidents = new HashMap<>();
presidents.put(new President("John Adams"), 18D);
presidents.put(new President("Barack Obama"), 21D);
@@ -466,59 +453,51 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
Message<Map<President, Double>> message = MessageBuilder.withPayload(presidents).setHeader("redis_key", key).build();
handler.handleMessage(message);
assertThat(redisZset.size()).isEqualTo(1);
this.deletePresidents(jcf);
assertThat(redisZset).hasSize(1);
RedisContainerTest.deletePresidents(redisConnectionFactory);
}
@Test(expected = IllegalStateException.class)
@RedisAvailable
public void testListWithMapKeyExpression() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
@Test
void testListWithMapKeyExpression() {
String key = "foo";
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setMapKeyExpression(new LiteralExpression(key));
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
assertThatThrownBy(handler::afterPropertiesSet).isInstanceOf(IllegalStateException.class);
}
@Test(expected = IllegalStateException.class)
@RedisAvailable
public void testSetWithMapKeyExpression() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
@Test
void testSetWithMapKeyExpression() {
String key = "foo";
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.SET);
handler.setMapKeyExpression(new LiteralExpression(key));
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
assertThatThrownBy(handler::afterPropertiesSet).isInstanceOf(IllegalStateException.class);
}
@Test(expected = IllegalStateException.class)
@RedisAvailable
public void testZsetWithMapKeyExpression() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
@Test
void testZsetWithMapKeyExpression() {
String key = "foo";
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.ZSET);
handler.setMapKeyExpression(new LiteralExpression(key));
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
assertThatThrownBy(handler::afterPropertiesSet).isInstanceOf(IllegalStateException.class);
}
@Test
@RedisAvailable
public void testMapWithMapKeyExpression() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testMapWithMapKeyExpression() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.MAP);
handler.setMapKeyExpression(new LiteralExpression(key));
@@ -529,17 +508,15 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
catch (Exception e) {
fail("No exception expected:" + e.getMessage());
}
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
@Test
@RedisAvailable
public void testPropertiesWithMapKeyExpression() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
this.deleteKey(jcf, "foo");
void testPropertiesWithMapKeyExpression() {
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
String key = "foo";
RedisStoreWritingMessageHandler handler =
new RedisStoreWritingMessageHandler(jcf);
new RedisStoreWritingMessageHandler(redisConnectionFactory);
handler.setKey(key);
handler.setCollectionType(CollectionType.PROPERTIES);
handler.setMapKeyExpression(new LiteralExpression(key));
@@ -550,7 +527,7 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
catch (Exception e) {
fail("No exception expected:" + e.getMessage());
}
this.deleteKey(jcf, "foo");
RedisContainerTest.deleteKey(redisConnectionFactory, "foo");
}
private <K, V> RedisTemplate<K, V> initTemplate(RedisConnectionFactory rcf, RedisTemplate<K, V> redisTemplate) {
@@ -562,6 +539,7 @@ public class RedisStoreWritingMessageHandlerTests extends RedisAvailableTests {
private static class President implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
President(String name) {

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.redis.rules;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Oleg Zhurakousky
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface RedisAvailable {
}

View File

@@ -1,100 +0,0 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.redis.rules;
import java.time.Duration;
import org.junit.Assume;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
/**
* @author Oleg Zhurakousky
* @author Gunnar Hillert
* @author Artem Bilan
* @author Marc Philipp
*/
public final class RedisAvailableRule implements MethodRule {
public static final int REDIS_PORT = 6379;
public static LettuceConnectionFactory connectionFactory;
private static volatile boolean initialized;
protected static void setupConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setPort(REDIS_PORT);
LettuceClientConfiguration clientConfiguration = LettuceClientConfiguration.builder()
.clientOptions(
ClientOptions.builder()
.socketOptions(
SocketOptions.builder()
.connectTimeout(Duration.ofMillis(10000))
.keepAlive(true)
.build())
.build())
.commandTimeout(Duration.ofSeconds(10000))
.build();
connectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfiguration);
connectionFactory.afterPropertiesSet();
}
public static void cleanUpConnectionFactoryIfAny() {
if (initialized) {
connectionFactory.destroy();
initialized = false;
}
}
public Statement apply(final Statement base, final FrameworkMethod method, Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
RedisAvailable redisAvailable = method.getAnnotation(RedisAvailable.class);
if (redisAvailable != null) {
if (connectionFactory != null) {
try {
connectionFactory.initConnection();
initialized = true;
}
catch (Exception e) {
Assume.assumeTrue(
"Skipping test due to Redis not being available on port: " + REDIS_PORT + ": " + e,
false);
}
base.evaluate();
}
}
}
};
}
}

View File

@@ -6,7 +6,8 @@
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd">
<beans:bean id="messageStore" class="org.springframework.integration.redis.store.RedisMessageStore">
<beans:constructor-arg value="#{T (org.springframework.integration.redis.rules.RedisAvailableRule).connectionFactory}"/>
<beans:constructor-arg
value="#{T (org.springframework.integration.redis.RedisContainerTest).connectionFactory()}"/>
</beans:bean>
<channel id="output">

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,19 +22,17 @@ import static org.assertj.core.api.Assertions.fail;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.integration.handler.DelayHandler;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.store.MessageGroup;
import org.springframework.integration.store.MessageGroupStore;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.support.LongRunningIntegrationTest;
import org.springframework.integration.test.condition.LongRunningTest;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
@@ -43,19 +41,16 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author Artem Bilan
* @author Gary Russell
* @author Artem Vozhdayenko
*
* @since 3.0
*/
public class DelayerHandlerRescheduleIntegrationTests extends RedisAvailableTests {
@LongRunningTest
class DelayerHandlerRescheduleIntegrationTests implements RedisContainerTest {
public static final String DELAYER_ID = "delayerWithRedisMS" + UUID.randomUUID();
@Rule
public LongRunningIntegrationTest longTests = new LongRunningIntegrationTest();
@Test
@RedisAvailable
public void testDelayerHandlerRescheduleWithRedisMessageStore() throws Exception {
void testDelayerHandlerRescheduleWithRedisMessageStore() throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"DelayerHandlerRescheduleIntegrationTests-context.xml", this.getClass());
MessageChannel input = context.getBean("input", MessageChannel.class);
@@ -75,7 +70,7 @@ public class DelayerHandlerRescheduleIntegrationTests extends RedisAvailableTest
ThreadPoolTaskScheduler taskScheduler =
(ThreadPoolTaskScheduler) IntegrationContextUtils.getTaskScheduler(context);
taskScheduler.shutdown();
taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS);
assertThat(taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS)).isTrue();
context.close();
try {
@@ -83,9 +78,8 @@ public class DelayerHandlerRescheduleIntegrationTests extends RedisAvailableTest
fail("IllegalStateException expected");
}
catch (Exception e) {
assertThat(e instanceof IllegalStateException).isTrue();
assertThat(e.getMessage().contains("BeanFactory not initialized or already closed - call 'refresh'"))
.isTrue();
assertThat(e).isInstanceOf(IllegalStateException.class);
assertThat(e.getMessage()).contains("BeanFactory not initialized or already closed - call 'refresh'");
}
assertThat(messageStore.getMessageGroupCount()).isEqualTo(1);
@@ -97,7 +91,7 @@ public class DelayerHandlerRescheduleIntegrationTests extends RedisAvailableTest
Object payload = messageInStore.getPayload();
// INT-3049
assertThat(payload instanceof DelayHandler.DelayedMessageWrapper).isTrue();
assertThat(payload).isInstanceOf(DelayHandler.DelayedMessageWrapper.class);
assertThat(((DelayHandler.DelayedMessageWrapper) payload).getOriginal()).isEqualTo(message1);
context.refresh();
@@ -119,7 +113,7 @@ public class DelayerHandlerRescheduleIntegrationTests extends RedisAvailableTest
while (n++ < 300 && messageStore.messageGroupSize(delayerMessageGroupId) > 0) {
Thread.sleep(100);
}
assertThat(messageStore.messageGroupSize(delayerMessageGroupId)).isEqualTo(0);
assertThat(messageStore.messageGroupSize(delayerMessageGroupId)).isZero();
messageStore.removeMessageGroup(delayerMessageGroupId);
context.close();

View File

@@ -2,24 +2,22 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<bean id="cms" class="org.springframework.integration.redis.store.RedisChannelMessageStore">
<constructor-arg ref="redisConnectionFactory"/>
</bean>
<int:channel id="testChannel1">
<int:queue message-store="cms" />
<int:queue message-store="cms"/>
</int:channel>
<int:channel id="testChannel2">
<int:queue message-store="cms" />
<int:queue message-store="cms"/>
</int:channel>
<bean id="priorityCms" class="org.springframework.integration.redis.store.RedisChannelPriorityMessageStore">
@@ -27,11 +25,11 @@
</bean>
<int:channel id="testChannel3">
<int:priority-queue message-store="priorityCms" />
<int:priority-queue message-store="priorityCms"/>
</int:channel>
<int:channel id="testChannel4">
<int:priority-queue message-store="priorityCms" />
<int:priority-queue message-store="priorityCms"/>
</int:channel>
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,35 +18,32 @@ package org.springframework.integration.redis.store;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.MutableMessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Gary Russell
* @author Artem Bilan
* @author Artem Vozhdayenko
*
* @since 4.0
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class RedisChannelMessageStoreTests extends RedisAvailableTests {
class RedisChannelMessageStoreTests implements RedisContainerTest {
@Autowired
private PollableChannel testChannel1;
@@ -66,9 +63,9 @@ public class RedisChannelMessageStoreTests extends RedisAvailableTests {
@Autowired
private RedisChannelMessageStore priorityCms;
@Before
@After
public void setUpTearDown() {
@BeforeEach
@AfterEach
void setUpTearDown() {
this.cms.removeMessageGroup("cms:testChannel1");
this.cms.removeMessageGroup("cms:testChannel2");
this.priorityCms.removeMessageGroup("priorityCms:testChannel3");
@@ -76,10 +73,9 @@ public class RedisChannelMessageStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testChannel() {
void testChannel() {
for (int i = 0; i < 10; i++) {
this.testChannel1.send(new GenericMessage<Integer>(i));
this.testChannel1.send(new GenericMessage<>(i));
}
assertThat(this.cms.getMessageGroupCount()).isEqualTo(1);
assertThat(this.cms.messageGroupSize("cms:testChannel1")).isEqualTo(10);
@@ -103,21 +99,20 @@ public class RedisChannelMessageStoreTests extends RedisAvailableTests {
assertThat(out.getPayload()).isEqualTo(i);
}
assertThat(this.testChannel2.receive(0)).isNull();
assertThat(this.cms.getMessageGroupCount()).isEqualTo(0);
assertThat(this.cms.getMessageGroupCount()).isZero();
for (int i = 0; i < 10; i++) {
this.testChannel1.send(new GenericMessage<Integer>(i));
this.testChannel1.send(new GenericMessage<>(i));
}
assertThat(this.cms.getMessageGroupCount()).isEqualTo(1);
assertThat(this.cms.messageGroupSize("cms:testChannel1")).isEqualTo(10);
this.cms.removeMessageGroup("cms:testChannel1");
assertThat(this.cms.getMessageGroupCount()).isEqualTo(0);
assertThat(this.cms.messageGroupSize("cms:testChannel1")).isEqualTo(0);
assertThat(this.cms.getMessageGroupCount()).isZero();
assertThat(this.cms.messageGroupSize("cms:testChannel1")).isZero();
}
@Test
@RedisAvailable
public void testPriority() {
void testPriority() {
for (int i = 0; i < 10; i++) {
this.testChannel3.send(MessageBuilder.withPayload(i).setPriority(i).build());
//We need unique messages
@@ -151,7 +146,7 @@ public class RedisChannelMessageStoreTests extends RedisAvailableTests {
assertThat(m).isNotNull();
assertThat(new IntegrationMessageHeaderAccessor(m).getPriority()).isNull();
assertThat(m.getPayload()).isEqualTo(98);
assertThat(this.priorityCms.messageGroupSize("priorityCms:testChannel3")).isEqualTo(0);
assertThat(this.priorityCms.messageGroupSize("priorityCms:testChannel3")).isZero();
m = this.testChannel4.receive(0);
assertThat(m).isNotNull();
@@ -159,19 +154,19 @@ public class RedisChannelMessageStoreTests extends RedisAvailableTests {
m = this.testChannel4.receive(0);
assertThat(m).isNotNull();
assertThat(new IntegrationMessageHeaderAccessor(m).getPriority()).isNull();
assertThat(this.priorityCms.getMessageGroupCount()).isEqualTo(0);
assertThat(this.priorityCms.getMessageCountForAllMessageGroups()).isEqualTo(0);
assertThat(this.priorityCms.getMessageGroupCount()).isZero();
assertThat(this.priorityCms.getMessageCountForAllMessageGroups()).isZero();
assertThat(this.testChannel3.receive(0)).isNull();
assertThat(this.testChannel4.receive(0)).isNull();
for (int i = 0; i < 10; i++) {
this.testChannel3.send(new GenericMessage<Integer>(i));
this.testChannel3.send(new GenericMessage<>(i));
}
assertThat(this.priorityCms.getMessageGroupCount()).isEqualTo(1);
assertThat(this.priorityCms.messageGroupSize("priorityCms:testChannel3")).isEqualTo(10);
this.priorityCms.removeMessageGroup("priorityCms:testChannel3");
assertThat(this.priorityCms.getMessageGroupCount()).isEqualTo(0);
assertThat(this.priorityCms.messageGroupSize("priorityCms:testChannel3")).isEqualTo(0);
assertThat(this.priorityCms.getMessageGroupCount()).isZero();
assertThat(this.priorityCms.messageGroupSize("priorityCms:testChannel3")).isZero();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007-2021 the original author or authors.
* Copyright 2007-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,10 +30,11 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -44,8 +45,7 @@ import org.springframework.integration.channel.NullChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.message.AdviceMessage;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.store.MessageGroup;
import org.springframework.integration.store.SimpleMessageGroup;
import org.springframework.integration.support.MessageBuilder;
@@ -63,35 +63,38 @@ import junit.framework.AssertionFailedError;
* @author Oleg Zhurakousky
* @author Artem Bilan
* @author Gary Russell
* @author Artem Vozhdayenko
*/
public class RedisMessageGroupStoreTests extends RedisAvailableTests {
class RedisMessageGroupStoreTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
private final UUID groupId = UUID.randomUUID();
@Before
@After
public void setUpTearDown() {
StringRedisTemplate template = createStringRedisTemplate(getConnectionFactoryForTest());
@BeforeEach
@AfterEach
void setUpTearDown() {
StringRedisTemplate template = RedisContainerTest.createStringRedisTemplate(redisConnectionFactory);
template.delete(template.keys("MESSAGE_GROUP_*"));
}
@Test
@RedisAvailable
public void testNonExistingEmptyMessageGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testNonExistingEmptyMessageGroup() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
MessageGroup messageGroup = store.getMessageGroup(this.groupId);
assertThat(messageGroup).isNotNull();
assertThat(messageGroup instanceof SimpleMessageGroup).isTrue();
assertThat(messageGroup.size()).isEqualTo(0);
assertThat(messageGroup).isInstanceOf(SimpleMessageGroup.class);
assertThat(messageGroup.size()).isZero();
}
@Test
@RedisAvailable
public void testMessageGroupUpdatedDateChangesWithEachAddedMessage() throws Exception {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testMessageGroupUpdatedDateChangesWithEachAddedMessage() throws Exception {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<?> message = new GenericMessage<>("Hello");
MessageGroup messageGroup = store.addMessageToGroup(this.groupId, message);
@@ -107,34 +110,30 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
assertThat(updatedTimestamp > createdTimestamp).isTrue();
// make sure the store is properly rebuild from Redis
store = new RedisMessageStore(jcf);
store = new RedisMessageStore(redisConnectionFactory);
messageGroup = store.getMessageGroup(this.groupId);
assertThat(messageGroup.size()).isEqualTo(2);
}
@Test
@RedisAvailable
public void testMessageGroupWithAddedMessage() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testMessageGroupWithAddedMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<?> message = new GenericMessage<>("Hello");
MessageGroup messageGroup = store.addMessageToGroup(this.groupId, message);
assertThat(messageGroup.size()).isEqualTo(1);
// make sure the store is properly rebuild from Redis
store = new RedisMessageStore(jcf);
store = new RedisMessageStore(redisConnectionFactory);
messageGroup = store.getMessageGroup(this.groupId);
assertThat(messageGroup.size()).isEqualTo(1);
}
@Test
@RedisAvailable
public void testRemoveMessageGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testRemoveMessageGroup() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
MessageGroup messageGroup = store.getMessageGroup(this.groupId);
Message<?> message = new GenericMessage<>("Hello");
@@ -145,23 +144,21 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
MessageGroup messageGroupA = store.getMessageGroup(this.groupId);
assertThat(messageGroupA).isNotSameAs(messageGroup);
// assertEquals(0, messageGroupA.getMarked().size());
assertThat(messageGroupA.getMessages().size()).isEqualTo(0);
assertThat(messageGroupA.size()).isEqualTo(0);
assertThat(messageGroupA.getMessages().size()).isZero();
assertThat(messageGroupA.size()).isZero();
// make sure the store is properly rebuild from Redis
store = new RedisMessageStore(jcf);
store = new RedisMessageStore(redisConnectionFactory);
messageGroup = store.getMessageGroup(this.groupId);
assertThat(messageGroup.getMessages().size()).isEqualTo(0);
assertThat(messageGroup.size()).isEqualTo(0);
assertThat(messageGroup.getMessages().size()).isZero();
assertThat(messageGroup.size()).isZero();
}
@Test
@RedisAvailable
public void testCompleteMessageGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testCompleteMessageGroup() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
MessageGroup messageGroup = store.getMessageGroup(this.groupId);
Message<?> message = new GenericMessage<>("Hello");
@@ -172,10 +169,8 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testLastReleasedSequenceNumber() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testLastReleasedSequenceNumber() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
MessageGroup messageGroup = store.getMessageGroup(this.groupId);
Message<?> message = new GenericMessage<>("Hello");
@@ -186,10 +181,8 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testRemoveMessageFromTheGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testRemoveMessageFromTheGroup() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
MessageGroup messageGroup = store.getMessageGroup(this.groupId);
Message<?> message = new GenericMessage<>("2");
@@ -202,17 +195,15 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
assertThat(messageGroup.size()).isEqualTo(2);
// make sure the store is properly rebuild from Redis
store = new RedisMessageStore(jcf);
store = new RedisMessageStore(redisConnectionFactory);
messageGroup = store.getMessageGroup(this.groupId);
assertThat(messageGroup.size()).isEqualTo(2);
}
@Test
@RedisAvailable
public void testWithMessageHistory() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testWithMessageHistory() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<?> message = new GenericMessage<>("Hello");
DirectChannel fooChannel = new DirectChannel();
@@ -230,15 +221,14 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
assertThat(messageHistory).isNotNull();
assertThat(messageHistory.size()).isEqualTo(2);
Properties fooChannelHistory = messageHistory.get(0);
assertThat(fooChannelHistory.get("name")).isEqualTo("fooChannel");
assertThat(fooChannelHistory.get("type")).isEqualTo("channel");
assertThat(fooChannelHistory)
.containsEntry("name", "fooChannel")
.containsEntry("type", "channel");
}
@Test
@RedisAvailable
public void testRemoveNonExistingMessageFromTheGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testRemoveNonExistingMessageFromTheGroup() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
MessageGroup messageGroup = store.getMessageGroup(this.groupId);
store.addMessagesToGroup(messageGroup.getGroupId(), new GenericMessage<>("1"));
@@ -246,21 +236,17 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testRemoveNonExistingMessageFromNonExistingTheGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testRemoveNonExistingMessageFromNonExistingTheGroup() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
store.removeMessagesFromGroup(this.groupId, new GenericMessage<>("2"));
}
@Test
@RedisAvailable
public void testMultipleInstancesOfGroupStore() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store1 = new RedisMessageStore(jcf);
void testMultipleInstancesOfGroupStore() {
RedisMessageStore store1 = new RedisMessageStore(redisConnectionFactory);
RedisMessageStore store2 = new RedisMessageStore(jcf);
RedisMessageStore store2 = new RedisMessageStore(redisConnectionFactory);
store1.removeMessageGroup(this.groupId);
@@ -270,7 +256,7 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
assertThat(messageGroup.getMessages().size()).isEqualTo(2);
RedisMessageStore store3 = new RedisMessageStore(jcf);
RedisMessageStore store3 = new RedisMessageStore(redisConnectionFactory);
store3.removeMessagesFromGroup(this.groupId, message);
messageGroup = store3.getMessageGroup(this.groupId);
@@ -279,11 +265,9 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testIteratorOfMessageGroups() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store1 = new RedisMessageStore(jcf);
RedisMessageStore store2 = new RedisMessageStore(jcf);
void testIteratorOfMessageGroups() {
RedisMessageStore store1 = new RedisMessageStore(redisConnectionFactory);
RedisMessageStore store2 = new RedisMessageStore(redisConnectionFactory);
store1.removeMessageGroup(this.groupId);
UUID group2 = UUID.randomUUID();
@@ -325,12 +309,10 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
@Ignore
public void testConcurrentModifications() throws Exception {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
final RedisMessageStore store1 = new RedisMessageStore(jcf);
final RedisMessageStore store2 = new RedisMessageStore(jcf);
@Disabled
void testConcurrentModifications() throws Exception {
final RedisMessageStore store1 = new RedisMessageStore(redisConnectionFactory);
final RedisMessageStore store2 = new RedisMessageStore(redisConnectionFactory);
store1.removeMessageGroup(this.groupId);
@@ -363,12 +345,11 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
executor.awaitTermination(10, TimeUnit.SECONDS);
store2.removeMessagesFromGroup(1, message); // ensures that if ADD thread executed after REMOVE, the store is empty for the next cycle
}
assertThat(failures.size() == 0).isTrue();
assertThat(failures).isEmpty();
}
@Test
@RedisAvailable
public void testWithAggregatorWithShutdown() {
void testWithAggregatorWithShutdown() {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("redis-aggregator-config.xml", getClass());
MessageChannel input = context.getBean("inputChannel", MessageChannel.class);
@@ -409,10 +390,8 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testAddAndRemoveMessagesFromMessageGroup() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore messageStore = new RedisMessageStore(jcf);
void testAddAndRemoveMessagesFromMessageGroup() {
RedisMessageStore messageStore = new RedisMessageStore(redisConnectionFactory);
List<Message<?>> messages = new ArrayList<Message<?>>();
for (int i = 0; i < 25; i++) {
Message<String> message = MessageBuilder.withPayload("foo").setCorrelationId(this.groupId).build();
@@ -423,15 +402,13 @@ public class RedisMessageGroupStoreTests extends RedisAvailableTests {
assertThat(group.size()).isEqualTo(25);
messageStore.removeMessagesFromGroup(this.groupId, messages);
group = messageStore.getMessageGroup(this.groupId);
assertThat(group.size()).isEqualTo(0);
assertThat(group.size()).isZero();
messageStore.removeMessageGroup(this.groupId);
}
@Test
@RedisAvailable
public void testJsonSerialization() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testJsonSerialization() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
ObjectMapper mapper = JacksonJsonUtils.messagingAwareMapper();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007-2020 the original author or authors.
* Copyright 2007-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,23 +17,24 @@
package org.springframework.integration.redis.store;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.util.Address;
import org.springframework.integration.redis.util.Person;
import org.springframework.integration.store.MessageGroup;
@@ -45,39 +46,40 @@ import org.springframework.messaging.support.GenericMessage;
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
* @author Artem Vozhdayenko
*
*/
public class RedisMessageStoreTests extends RedisAvailableTests {
class RedisMessageStoreTests implements RedisContainerTest {
private static RedisConnectionFactory redisConnectionFactory;
@Before
@After
@BeforeAll
static void setupConnection() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@BeforeEach
@AfterEach
public void setUpTearDown() {
StringRedisTemplate template = this.createStringRedisTemplate(this.getConnectionFactoryForTest());
StringRedisTemplate template = RedisContainerTest.createStringRedisTemplate(redisConnectionFactory);
template.delete(template.keys("*MESSAGE_*"));
}
@Test
@RedisAvailable
public void testGetNonExistingMessage() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testGetNonExistingMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<?> message = store.getMessage(UUID.randomUUID());
assertThat(message).isNull();
}
@Test
@RedisAvailable
public void testGetMessageCountWhenEmpty() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
assertThat(store.getMessageCount()).isEqualTo(0);
void testGetMessageCountWhenEmpty() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
assertThat(store.getMessageCount()).isZero();
}
@Test
@RedisAvailable
public void testAddStringMessage() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testAddStringMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<String> stringMessage = new GenericMessage<>("Hello Redis");
Message<String> storedMessage = store.addMessage(stringMessage);
assertThat(storedMessage).isNotSameAs(stringMessage);
@@ -85,10 +87,8 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testAddSerializableObjectMessage() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testAddSerializableObjectMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Address address = new Address();
address.setAddress("1600 Pennsylvania Av, Washington, DC");
Person person = new Person(address, "Barak Obama");
@@ -99,22 +99,19 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
assertThat(storedMessage.getPayload().getName()).isEqualTo("Barak Obama");
}
@Test(expected = IllegalArgumentException.class)
@RedisAvailable
public void testAddNonSerializableObjectMessage() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
@Test
void testAddNonSerializableObjectMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<Foo> objectMessage = new GenericMessage<>(new Foo());
store.addMessage(objectMessage);
assertThatThrownBy(() -> store.addMessage(objectMessage)).isInstanceOf(IllegalArgumentException.class);
}
@SuppressWarnings("unchecked")
@Test
@RedisAvailable
public void testAddAndGetStringMessage() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testAddAndGetStringMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<String> stringMessage = new GenericMessage<>("Hello Redis");
store.addMessage(stringMessage);
Message<String> retrievedMessage = (Message<String>) store.getMessage(stringMessage.getHeaders().getId());
@@ -124,17 +121,15 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
@SuppressWarnings("unchecked")
@Test
@RedisAvailable
public void testAddAndGetWithPrefix() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf, "foo");
void testAddAndGetWithPrefix() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory, "foo");
Message<String> stringMessage = new GenericMessage<>("Hello Redis");
store.addMessage(stringMessage);
Message<String> retrievedMessage = (Message<String>) store.getMessage(stringMessage.getHeaders().getId());
assertThat(retrievedMessage).isNotNull();
assertThat(retrievedMessage.getPayload()).isEqualTo("Hello Redis");
StringRedisTemplate template = createStringRedisTemplate(getConnectionFactoryForTest());
StringRedisTemplate template = RedisContainerTest.createStringRedisTemplate(redisConnectionFactory);
BoundValueOperations<String, String> ops =
template.boundValueOps("foo" + "MESSAGE_" + stringMessage.getHeaders().getId());
assertThat(ops.get()).isNotNull();
@@ -142,10 +137,8 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
@SuppressWarnings("unchecked")
@Test
@RedisAvailable
public void testAddAndRemoveStringMessage() {
RedisConnectionFactory jcf = getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testAddAndRemoveStringMessage() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<String> stringMessage = new GenericMessage<>("Hello Redis");
store.addMessage(stringMessage);
Message<String> retrievedMessage = (Message<String>) store.removeMessage(stringMessage.getHeaders().getId());
@@ -155,10 +148,8 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testWithMessageHistory() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMessageStore store = new RedisMessageStore(jcf);
void testWithMessageHistory() {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory);
Message<?> message = new GenericMessage<>("Hello");
DirectChannel fooChannel = new DirectChannel();
@@ -174,15 +165,14 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
assertThat(messageHistory).isNotNull();
assertThat(messageHistory.size()).isEqualTo(2);
Properties fooChannelHistory = messageHistory.get(0);
assertThat(fooChannelHistory.get("name")).isEqualTo("fooChannel");
assertThat(fooChannelHistory.get("type")).isEqualTo("channel");
assertThat(fooChannelHistory)
.containsEntry("name", "fooChannel")
.containsEntry("type", "channel");
}
@Test
@RedisAvailable
public void testAddAndRemoveMessagesFromMessageGroup() {
RedisConnectionFactory jcf = this.getConnectionFactoryForTest();
RedisMessageStore messageStore = new RedisMessageStore(jcf);
void testAddAndRemoveMessagesFromMessageGroup() {
RedisMessageStore messageStore = new RedisMessageStore(redisConnectionFactory);
String groupId = "X";
List<Message<?>> messages = new ArrayList<>();
for (int i = 0; i < 25; i++) {
@@ -192,7 +182,7 @@ public class RedisMessageStoreTests extends RedisAvailableTests {
}
messageStore.removeMessagesFromGroup(groupId, messages);
MessageGroup group = messageStore.getMessageGroup(groupId);
assertThat(group.size()).isEqualTo(0);
assertThat(group.size()).isZero();
messageStore.removeMessageGroup("X");
}

View File

@@ -12,7 +12,7 @@
</int:channel>
<bean id="redisStore" class="org.springframework.integration.redis.store.RedisMessageStore">
<constructor-arg value="#{T (org.springframework.integration.redis.rules.RedisAvailableRule).connectionFactory}"/>
<constructor-arg value="#{T (org.springframework.integration.redis.RedisContainerTest).connectionFactory()}"/>
</bean>
</beans>

View File

@@ -2,38 +2,37 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd">
<util:constant id="redisConnectionFactory"
static-field="org.springframework.integration.redis.rules.RedisAvailableRule.connectionFactory"/>
<bean id="redisConnectionFactory" class="org.springframework.integration.redis.RedisContainerTest"
factory-method="connectionFactory"/>
<int:aggregator input-channel="in" release-strategy="latching" output-channel="out"
message-store="sms"
expire-groups-upon-completion="true" lock-registry="redisLockRegistry" />
message-store="sms"
expire-groups-upon-completion="true" lock-registry="redisLockRegistry"/>
<bean id="latching" class="org.springframework.integration.redis.util.AggregatorWithRedisLocksTests$LatchingReleaseStrategy" />
<bean id="latching"
class="org.springframework.integration.redis.util.AggregatorWithRedisLocksTests$LatchingReleaseStrategy"/>
<bean id="redisLockRegistry" class="org.springframework.integration.redis.util.RedisLockRegistry">
<constructor-arg ref="redisConnectionFactory"/>
<constructor-arg value="aggregatorWithRedisLocksTests" />
<constructor-arg value="aggregatorWithRedisLocksTests"/>
</bean>
<bean id="sms" class="org.springframework.integration.store.SimpleMessageStore" />
<bean id="sms" class="org.springframework.integration.store.SimpleMessageStore"/>
<int:aggregator input-channel="in2" release-strategy="latching" output-channel="out"
message-store="sms"
expire-groups-upon-completion="true" lock-registry="redisLockRegistry2" />
message-store="sms"
expire-groups-upon-completion="true" lock-registry="redisLockRegistry2"/>
<bean id="redisLockRegistry2" class="org.springframework.integration.redis.util.RedisLockRegistry">
<constructor-arg ref="redisConnectionFactory"/>
<constructor-arg value="aggregatorWithRedisLocksTests" />
<constructor-arg value="aggregatorWithRedisLocksTests"/>
</bean>
<int:channel id="out">
<int:queue />
<int:queue/>
</int:channel>
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,37 +26,35 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.aggregator.ReleaseStrategy;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.store.MessageGroup;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Gary Russell
* @author Artem Bilan
* @since 4.0
* @author Artem Vozhdayenko
*
* @since 4.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
class AggregatorWithRedisLocksTests implements RedisContainerTest {
@Autowired
private LatchingReleaseStrategy releaseStrategy;
@@ -70,12 +68,15 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
@Autowired
private PollableChannel out;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
private volatile Exception exception;
private RedisTemplate<String, ?> template;
@Before
@After
@BeforeEach
@AfterEach
public void setup() {
this.template = this.createTemplate();
Set<String> keys = template.keys("aggregatorWithRedisLocksTests:*");
@@ -85,13 +86,12 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testLockSingleGroup() throws Exception {
void testLockSingleGroup() throws Exception {
this.releaseStrategy.reset(1);
Executors.newSingleThreadExecutor().execute(asyncSend("foo", 1, 1));
Executors.newSingleThreadExecutor().execute(asyncSend("bar", 2, 1));
assertThat(this.releaseStrategy.latch2.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*").size()).isEqualTo(1);
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*")).hasSize(1);
this.releaseStrategy.latch1.countDown();
assertThat(this.out.receive(10000)).isNotNull();
assertThat(this.releaseStrategy.maxCallers.get()).isEqualTo(1);
@@ -101,8 +101,7 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testLockThreeGroups() throws Exception {
void testLockThreeGroups() throws Exception {
this.releaseStrategy.reset(3);
Executors.newSingleThreadExecutor().execute(asyncSend("foo", 1, 1));
Executors.newSingleThreadExecutor().execute(asyncSend("bar", 2, 1));
@@ -111,7 +110,7 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
Executors.newSingleThreadExecutor().execute(asyncSend("foo", 1, 3));
Executors.newSingleThreadExecutor().execute(asyncSend("bar", 2, 3));
assertThat(this.releaseStrategy.latch2.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*").size()).isEqualTo(3);
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*")).hasSize(3);
this.releaseStrategy.latch1.countDown();
this.releaseStrategy.latch1.countDown();
this.releaseStrategy.latch1.countDown();
@@ -124,22 +123,20 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
.as("Unexpected exception:" + (this.exception != null ? this.exception.toString() : "")).isNull();
}
@Test
@RedisAvailable
@Repeat(10)
public void testDistributedAggregator() throws Exception {
@RepeatedTest(10)
void testDistributedAggregator() throws Exception {
this.releaseStrategy.reset(1);
Executors.newSingleThreadExecutor().execute(asyncSend("foo", 1, 1));
Executors.newSingleThreadExecutor().execute(() -> {
try {
in2.send(new GenericMessage<String>("bar", stubHeaders(2, 2, 1)));
in2.send(new GenericMessage<>("bar", stubHeaders(2, 2, 1)));
}
catch (Exception e) {
exception = e;
}
});
assertThat(this.releaseStrategy.latch2.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*").size()).isEqualTo(1);
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*")).hasSize(1);
this.releaseStrategy.latch1.countDown();
assertThat(this.out.receive(10000)).isNotNull();
assertThat(this.releaseStrategy.maxCallers.get()).isEqualTo(1);
@@ -153,13 +150,13 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
while (n++ < 100 && this.template.keys("aggregatorWithRedisLocksTests:*").size() > 0) {
Thread.sleep(100);
}
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*").size()).isEqualTo(0);
assertThat(this.template.keys("aggregatorWithRedisLocksTests:*")).isEmpty();
}
private Runnable asyncSend(final String payload, final int sequence, final int correlation) {
return () -> {
try {
in.send(new GenericMessage<String>(payload, stubHeaders(sequence, 2, correlation)));
in.send(new GenericMessage<>(payload, stubHeaders(sequence, 2, correlation)));
}
catch (Exception e) {
exception = e;
@@ -168,7 +165,7 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
}
private Map<String, Object> stubHeaders(int sequenceNumber, int sequenceSize, int correlationId) {
Map<String, Object> headers = new HashMap<String, Object>();
var headers = new HashMap<String, Object>();
headers.put(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, sequenceNumber);
headers.put(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE, sequenceSize);
headers.put(IntegrationMessageHeaderAccessor.CORRELATION_ID, correlationId);
@@ -176,8 +173,8 @@ public class AggregatorWithRedisLocksTests extends RedisAvailableTests {
}
private RedisTemplate<String, ?> createTemplate() {
RedisTemplate<String, ?> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(this.getConnectionFactoryForTest());
var template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;

View File

@@ -19,7 +19,6 @@ package org.springframework.integration.redis.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Queue;
@@ -41,17 +40,15 @@ import java.util.stream.IntStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.integration.redis.rules.RedisAvailable;
import org.springframework.integration.redis.rules.RedisAvailableTests;
import org.springframework.integration.redis.RedisContainerTest;
import org.springframework.integration.redis.util.RedisLockRegistry.RedisLockType;
import org.springframework.integration.test.util.TestUtils;
@@ -61,18 +58,12 @@ import org.springframework.integration.test.util.TestUtils;
* @author Artem Bilan
* @author Vedran Pavic
* @author Unseok Kim
* @author Artem Vozhdayenko
*
* @since 4.0
*
*/
@RunWith(Parameterized.class)
public class RedisLockRegistryTests extends RedisAvailableTests {
private final RedisLockType testRedisLockType;
public RedisLockRegistryTests(RedisLockType redisLockType) {
this.testRedisLockType = redisLockType;
}
class RedisLockRegistryTests implements RedisContainerTest {
private final Log logger = LogFactory.getLog(getClass());
@@ -80,65 +71,67 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
private final String registryKey2 = UUID.randomUUID().toString();
@Parameters
public static Collection<RedisLockType> getRedisLockTypeParameters() {
return List.of(RedisLockType.values());
private static RedisConnectionFactory redisConnectionFactory;
@BeforeAll
static void setupConnections() {
redisConnectionFactory = RedisContainerTest.connectionFactory();
}
@Before
@After
public void setupShutDown() {
@BeforeEach
@AfterEach
void setupShutDown() {
StringRedisTemplate template = this.createTemplate();
template.delete(this.registryKey + ":*");
template.delete(this.registryKey2 + ":*");
}
private StringRedisTemplate createTemplate() {
return new StringRedisTemplate(getConnectionFactoryForTest());
return new StringRedisTemplate(redisConnectionFactory);
}
@Test
@RedisAvailable
public void testLock() {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testLock(RedisLockType testRedisLockType) {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
for (int i = 0; i < 10; i++) {
Lock lock = registry.obtain("foo");
lock.lock();
try {
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(1);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(1);
}
finally {
lock.unlock();
}
}
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testLockInterruptibly() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testLockInterruptibly(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
for (int i = 0; i < 10; i++) {
Lock lock = registry.obtain("foo");
lock.lockInterruptibly();
try {
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(1);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(1);
}
finally {
lock.unlock();
}
}
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testReentrantLock() {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testReentrantLock(RedisLockType testRedisLockType) {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
for (int i = 0; i < 10; i++) {
Lock lock1 = registry.obtain("foo");
@@ -159,13 +152,13 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
}
}
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testReentrantLockInterruptibly() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testReentrantLockInterruptibly(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
for (int i = 0; i < 10; i++) {
Lock lock1 = registry.obtain("foo");
@@ -186,13 +179,13 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
}
}
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testTwoLocks() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testTwoLocks(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
for (int i = 0; i < 10; i++) {
Lock lock1 = registry.obtain("foo");
@@ -213,13 +206,13 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
}
}
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testTwoThreadsSecondFailsToGetLock() throws Exception {
final RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testTwoThreadsSecondFailsToGetLock(RedisLockType testRedisLockType) throws Exception {
final RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
final Lock lock1 = registry.obtain("foo");
lock1.lockInterruptibly();
@@ -244,13 +237,13 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
assertThat(ise).isInstanceOf(IllegalStateException.class);
assertThat(((Exception) ise).getMessage()).contains("You do not own lock at");
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testTwoThreads() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testTwoThreads(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
Lock lock1 = registry.obtain("foo");
AtomicBoolean locked = new AtomicBoolean();
@@ -258,13 +251,13 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
CountDownLatch latch2 = new CountDownLatch(1);
CountDownLatch latch3 = new CountDownLatch(1);
lock1.lockInterruptibly();
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(1);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(1);
Executors.newSingleThreadExecutor().execute(() -> {
Lock lock2 = registry.obtain("foo");
try {
latch1.countDown();
lock2.lockInterruptibly();
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(1);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(1);
latch2.await(10, TimeUnit.SECONDS);
locked.set(true);
}
@@ -283,15 +276,15 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
assertThat(latch3.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(locked.get()).isTrue();
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testTwoThreadsDifferentRegistries() throws Exception {
RedisLockRegistry registry1 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testTwoThreadsDifferentRegistries(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry1 = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry1.setRedisLockType(testRedisLockType);
RedisLockRegistry registry2 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
RedisLockRegistry registry2 = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry2.setRedisLockType(testRedisLockType);
Lock lock1 = registry1.obtain("foo");
AtomicBoolean locked = new AtomicBoolean();
@@ -299,13 +292,13 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
CountDownLatch latch2 = new CountDownLatch(1);
CountDownLatch latch3 = new CountDownLatch(1);
lock1.lockInterruptibly();
assertThat(TestUtils.getPropertyValue(registry1, "locks", Map.class).size()).isEqualTo(1);
assertThat(getRedisLockRegistryLocks(registry1)).hasSize(1);
Executors.newSingleThreadExecutor().execute(() -> {
Lock lock2 = registry2.obtain("foo");
try {
latch1.countDown();
lock2.lockInterruptibly();
assertThat(TestUtils.getPropertyValue(registry2, "locks", Map.class).size()).isEqualTo(1);
assertThat(getRedisLockRegistryLocks(registry2)).hasSize(1);
latch2.await(10, TimeUnit.SECONDS);
locked.set(true);
}
@@ -331,14 +324,14 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
assertThat(locked.get()).isTrue();
registry1.expireUnusedOlderThan(-1000);
registry2.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry1, "locks", Map.class).size()).isEqualTo(0);
assertThat(TestUtils.getPropertyValue(registry2, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry1)).isEmpty();
assertThat(getRedisLockRegistryLocks(registry2)).isEmpty();
}
@Test
@RedisAvailable
public void testTwoThreadsWrongOneUnlocks() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testTwoThreadsWrongOneUnlocks(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry.setRedisLockType(testRedisLockType);
Lock lock = registry.obtain("foo");
lock.lockInterruptibly();
@@ -361,15 +354,15 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
assertThat(ise).isInstanceOf(IllegalStateException.class);
assertThat(((Exception) ise).getMessage()).contains("You do not own lock at");
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void testExpireTwoRegistries() throws Exception {
RedisLockRegistry registry1 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 100);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testExpireTwoRegistries(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry1 = new RedisLockRegistry(redisConnectionFactory, this.registryKey, 100);
registry1.setRedisLockType(testRedisLockType);
RedisLockRegistry registry2 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 100);
RedisLockRegistry registry2 = new RedisLockRegistry(redisConnectionFactory, this.registryKey, 100);
registry2.setRedisLockType(testRedisLockType);
Lock lock1 = registry1.obtain("foo");
Lock lock2 = registry2.obtain("foo");
@@ -380,10 +373,10 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
assertThat(lock1.tryLock()).isFalse();
}
@Test
@RedisAvailable
public void testExceptionOnExpire() throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 1);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testExceptionOnExpire(RedisLockType testRedisLockType) throws Exception {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey, 1);
registry.setRedisLockType(testRedisLockType);
Lock lock1 = registry.obtain("foo");
assertThat(lock1.tryLock()).isTrue();
@@ -394,10 +387,10 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void testEquals() {
RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testEquals(RedisLockType testRedisLockType) {
RedisConnectionFactory connectionFactory = redisConnectionFactory;
RedisLockRegistry registry1 = new RedisLockRegistry(connectionFactory, this.registryKey);
registry1.setRedisLockType(testRedisLockType);
RedisLockRegistry registry2 = new RedisLockRegistry(connectionFactory, this.registryKey);
@@ -431,34 +424,34 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
lock2.unlock();
}
@Test
@RedisAvailable
public void testThreadLocalListLeaks() {
RedisLockRegistry registry = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 10000);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testThreadLocalListLeaks(RedisLockType testRedisLockType) {
RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, this.registryKey, 10000);
registry.setRedisLockType(testRedisLockType);
for (int i = 0; i < 10; i++) {
registry.obtain("foo" + i);
}
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(10);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(10);
for (int i = 0; i < 10; i++) {
Lock lock = registry.obtain("foo" + i);
lock.lock();
}
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(10);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(10);
for (int i = 0; i < 10; i++) {
Lock lock = registry.obtain("foo" + i);
lock.unlock();
}
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(10);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(10);
}
@Test
@RedisAvailable
public void testExpireNotChanged() throws Exception {
RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
@ParameterizedTest
@EnumSource(RedisLockType.class)
void testExpireNotChanged(RedisLockType testRedisLockType) throws Exception {
RedisConnectionFactory connectionFactory = redisConnectionFactory;
final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000);
registry.setRedisLockType(testRedisLockType);
@@ -477,15 +470,15 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
lock.unlock();
}
@Test
@RedisAvailable
public void concurrentObtainCapacityTest() throws InterruptedException {
@ParameterizedTest
@EnumSource(RedisLockType.class)
void concurrentObtainCapacityTest(RedisLockType testRedisLockType) throws InterruptedException {
final int KEY_CNT = 500;
final int CAPACITY_CNT = 179;
final int THREAD_CNT = 4;
final CountDownLatch countDownLatch = new CountDownLatch(THREAD_CNT);
final RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
final RedisConnectionFactory connectionFactory = redisConnectionFactory;
final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000);
registry.setCacheCapacity(CAPACITY_CNT);
registry.setRedisLockType(testRedisLockType);
@@ -512,23 +505,23 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
executorService.awaitTermination(5, TimeUnit.SECONDS);
//capacity limit test
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(CAPACITY_CNT);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(CAPACITY_CNT);
registry.expireUnusedOlderThan(-1000);
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(0);
assertThat(getRedisLockRegistryLocks(registry)).isEmpty();
}
@Test
@RedisAvailable
public void concurrentObtainRemoveOrderTest() throws InterruptedException {
@ParameterizedTest
@EnumSource(RedisLockType.class)
void concurrentObtainRemoveOrderTest(RedisLockType testRedisLockType) throws InterruptedException {
final int THREAD_CNT = 2;
final int DUMMY_LOCK_CNT = 3;
final int CAPACITY_CNT = THREAD_CNT;
final CountDownLatch countDownLatch = new CountDownLatch(THREAD_CNT);
final RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
final RedisConnectionFactory connectionFactory = redisConnectionFactory;
final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000);
registry.setCacheCapacity(CAPACITY_CNT);
registry.setRedisLockType(testRedisLockType);
@@ -568,9 +561,9 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
remainLockCheckQueue.toArray(new String[remainLockCheckQueue.size()]));
}
@Test
@RedisAvailable
public void concurrentObtainAccessRemoveOrderTest() throws InterruptedException {
@ParameterizedTest
@EnumSource(RedisLockType.class)
void concurrentObtainAccessRemoveOrderTest(RedisLockType testRedisLockType) throws InterruptedException {
final int THREAD_CNT = 2;
final int DUMMY_LOCK_CNT = 3;
@@ -578,7 +571,7 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
final String REMAIN_DUMMY_LOCK_KEY = "foo:1";
final CountDownLatch countDownLatch = new CountDownLatch(THREAD_CNT);
final RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
final RedisConnectionFactory connectionFactory = redisConnectionFactory;
final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000);
registry.setCacheCapacity(CAPACITY_CNT);
registry.setRedisLockType(testRedisLockType);
@@ -623,11 +616,11 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
remainLockCheckQueue.toArray(new String[remainLockCheckQueue.size()]));
}
@Test
@RedisAvailable
public void setCapacityTest() {
@ParameterizedTest
@EnumSource(RedisLockType.class)
void setCapacityTest(RedisLockType testRedisLockType) {
final int CAPACITY_CNT = 4;
final RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
final RedisConnectionFactory connectionFactory = redisConnectionFactory;
final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000);
registry.setCacheCapacity(CAPACITY_CNT);
registry.setRedisLockType(testRedisLockType);
@@ -641,23 +634,22 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
registry.obtain("foo:4");
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(3);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(3);
assertThat(getRedisLockRegistryLocks(registry)).containsKeys("foo:2", "foo:3", "foo:4");
//capacity 3->4
registry.setCacheCapacity(CAPACITY_CNT);
registry.obtain("foo:5");
assertThat(TestUtils.getPropertyValue(registry, "locks", Map.class).size()).isEqualTo(4);
assertThat(getRedisLockRegistryLocks(registry)).hasSize(4);
assertThat(getRedisLockRegistryLocks(registry)).containsKeys("foo:3", "foo:4", "foo:5");
}
@RedisAvailable
@Test
public void twoRedisLockRegistryTest() throws InterruptedException {
RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
RedisLockRegistry registry1 = new RedisLockRegistry(connectionFactory, registryKey, 1000000L);
@ParameterizedTest
@EnumSource(RedisLockType.class)
void twoRedisLockRegistryTest(RedisLockType testRedisLockType) throws InterruptedException {
RedisLockRegistry registry1 = new RedisLockRegistry(redisConnectionFactory, registryKey, 1000000L);
registry1.setRedisLockType(testRedisLockType);
RedisLockRegistry registry2 = new RedisLockRegistry(connectionFactory, registryKey, 1000000L);
RedisLockRegistry registry2 = new RedisLockRegistry(redisConnectionFactory, registryKey, 1000000L);
registry2.setRedisLockType(testRedisLockType);
String lockKey = "test-1";
@@ -668,7 +660,7 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
CountDownLatch registry1Lock = new CountDownLatch(1);
CountDownLatch endDownLatch = new CountDownLatch(2);
CompletableFuture.runAsync(() -> {
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
try {
obtainLock_1.lock();
// for (int i = 0; i < 10; i++) {
@@ -683,7 +675,7 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
}
});
CompletableFuture.runAsync(() -> {
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
try {
registry1Lock.await();
}
@@ -695,12 +687,14 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
});
endDownLatch.await();
assertThat(future1).isNotCompletedExceptionally();
assertThat(future2).isNotCompletedExceptionally();
}
@RedisAvailable
@Test
public void multiRedisLockRegistryTest() throws InterruptedException, ExecutionException {
final RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
@ParameterizedTest
@EnumSource(RedisLockType.class)
void multiRedisLockRegistryTest(RedisLockType testRedisLockType) throws InterruptedException, ExecutionException {
final String testKey = "testKey";
final long expireAfter = 100000L;
final int lockRegistryNum = 10;
@@ -708,7 +702,7 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
final AtomicInteger atomicInteger = new AtomicInteger(0);
final List<Callable<Boolean>> collect = IntStream.range(0, lockRegistryNum)
.mapToObj((num) -> new RedisLockRegistry(
connectionFactory, registryKey, expireAfter))
redisConnectionFactory, registryKey, expireAfter))
.map((registry) -> {
registry.setRedisLockType(testRedisLockType);
final Callable<Boolean> callable = () -> {
@@ -734,20 +728,19 @@ public class RedisLockRegistryTests extends RedisAvailableTests {
}
@Test
@RedisAvailable
public void earlyWakeUpTest() throws InterruptedException {
@ParameterizedTest
@EnumSource(RedisLockType.class)
void earlyWakeUpTest(RedisLockType testRedisLockType) throws InterruptedException {
final int THREAD_CNT = 2;
final String testKey = "testKey";
final CountDownLatch tryLockReady = new CountDownLatch(THREAD_CNT);
final CountDownLatch awaitTimeout = new CountDownLatch(THREAD_CNT);
final RedisConnectionFactory connectionFactory = getConnectionFactoryForTest();
final RedisLockRegistry registry1 = new RedisLockRegistry(connectionFactory, this.registryKey);
final RedisLockRegistry registry1 = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry1.setRedisLockType(testRedisLockType);
final RedisLockRegistry registry2 = new RedisLockRegistry(connectionFactory, this.registryKey);
final RedisLockRegistry registry2 = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry2.setRedisLockType(testRedisLockType);
final RedisLockRegistry registry3 = new RedisLockRegistry(connectionFactory, this.registryKey);
final RedisLockRegistry registry3 = new RedisLockRegistry(redisConnectionFactory, this.registryKey);
registry3.setRedisLockType(testRedisLockType);
final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_CNT);