redis 测试类进行测试

This commit is contained in:
YuCheng Hu 2023-01-17 14:18:04 -05:00
parent 4711c3a393
commit 1b3b30cae3
28 changed files with 863 additions and 7 deletions

View File

@ -17,6 +17,7 @@
<module name="core-java-8-2" />
<module name="core-java-numbers" />
<module name="discourse" />
<module name="spring-data-redis" />
<module name="core-java-strings" />
<module name="core-java" />
<module name="core-java-11" />

View File

@ -43,6 +43,8 @@
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />

View File

@ -1,6 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="ossez-repo-snapshots" />
<option name="name" value="OSSEZ Private Snapshots" />
<option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
@ -11,6 +16,16 @@
<option name="name" value="GeoDB repository" />
<option name="url" value="http://repo.boundlessgeo.com/main/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossez-repo-releases" />
<option name="name" value="OSSEZ Private Releases" />
<option name="url" value="https://repo.ossez.com/repository/maven-releases/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.ossez.com/repository/maven-public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />

7
.idea/jpa-buddy.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JpaBuddyIdeaProjectConfig">
<option name="defaultUnitInitialized" value="true" />
<option name="renamerInitialized" value="true" />
</component>
</project>

12
.idea/php.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>

View File

@ -76,7 +76,7 @@
<!-- <module>spring-data-keyvalue</module>-->
<!-- <module>spring-data-mongodb</module>-->
<!-- <module>spring-data-neo4j</module>-->
<!-- <module>spring-data-redis</module>-->
<module>spring-data-redis</module>
<!-- <module>spring-data-solr</module>-->
<!-- <module>spring-hibernate-3</module>-->
<!-- <module>spring-hibernate-5</module> &lt;!&ndash; long running &ndash;&gt;-->

View File

@ -0,0 +1,16 @@
## Spring Data Redis
### 相关文章:
- [Introduction to Spring Data Redis](https://www.baeldung.com/spring-data-redis-tutorial)
- [PubSub Messaging with Spring Data Redis](https://www.baeldung.com/spring-data-redis-pub-sub)
- [An Introduction to Spring Data Redis Reactive](https://www.baeldung.com/spring-data-redis-reactive)
### 构建项目并且运行所有的测试
```
mvn clean install
```
### 只运行测试
```
mvn test
```

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-redis</artifactId>
<version>1.0</version>
<name>spring-data-redis</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-redis</artifactId>
<version>${nosqlunit.version}</version>
</dependency>
<dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>
<version>${embedded-redis.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<verbose>true</verbose>
<fork>false</fork>
<forkCount>0</forkCount>
<argLine>-Xmx1024m</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<cglib.version>3.2.4</cglib.version>
<nosqlunit.version>0.10.0</nosqlunit.version>
<embedded-redis.version>0.6</embedded-redis.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.data.reactive.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRedisReactiveApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedisReactiveApplication.class, args);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.spring.data.reactive.redis.config;
import com.baeldung.spring.data.reactive.redis.model.Employee;
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.ReactiveKeyCommands;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.ReactiveStringCommands;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PreDestroy;
@Configuration
public class RedisConfig {
@Autowired
RedisConnectionFactory factory;
@Bean
public ReactiveRedisTemplate<String, Employee> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<>(Employee.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, Employee> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Employee> context = builder.value(serializer)
.build();
return new ReactiveRedisTemplate<>(factory, context);
}
@Bean
public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection()
.keyCommands();
}
@Bean
public ReactiveStringCommands stringCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection()
.stringCommands();
}
@PreDestroy
public void cleanRedis() {
factory.getConnection()
.flushDb();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.spring.data.reactive.redis.model;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Employee implements Serializable {
private static final long serialVersionUID = 1603714798906422731L;
private String id;
private String name;
private String department;
}

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.data.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedisApplication.class, args);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.spring.data.redis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import com.baeldung.spring.data.redis.queue.MessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
@Configuration
@ComponentScan("com.baeldung.spring.data.redis")
@EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo")
@PropertySource("classpath:application.properties")
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
return template;
}
@Bean
MessageListenerAdapter messageListener() {
return new MessageListenerAdapter(new RedisMessageSubscriber());
}
@Bean
RedisMessageListenerContainer redisContainer() {
final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
container.addMessageListener(messageListener(), topic());
return container;
}
@Bean
MessagePublisher redisPublisher() {
return new RedisMessagePublisher(redisTemplate(), topic());
}
@Bean
ChannelTopic topic() {
return new ChannelTopic("pubsub:queue");
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.spring.data.redis.model;
import java.io.Serializable;
import org.springframework.data.redis.core.RedisHash;
@RedisHash("Student")
public class Student implements Serializable {
public enum Gender {
MALE, FEMALE
}
private String id;
private String name;
private Gender gender;
private int grade;
public Student(String id, String name, Gender gender, int grade) {
this.id = id;
this.name = name;
this.gender = gender;
this.grade = grade;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", gender=" + gender + ", grade=" + grade + '}';
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.spring.data.redis.queue;
public interface MessagePublisher {
void publish(final String message);
}

View File

@ -0,0 +1,27 @@
package com.baeldung.spring.data.redis.queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Service;
@Service
public class RedisMessagePublisher implements MessagePublisher {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ChannelTopic topic;
public RedisMessagePublisher() {
}
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate, final ChannelTopic topic) {
this.redisTemplate = redisTemplate;
this.topic = topic;
}
public void publish(final String message) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.spring.data.redis.queue;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class RedisMessageSubscriber implements MessageListener {
public static List<String> messageList = new ArrayList<String>();
public void onMessage(final Message message, final byte[] pattern) {
messageList.add(message.toString());
System.out.println("Message received: " + new String(message.getBody()));
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.spring.data.redis.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.spring.data.redis.model.Student;
@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}

View File

@ -0,0 +1,2 @@
spring.redis.host=localhost
spring.redis.port=6379

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Binary file not shown.

After

Width:  |  Height:  |  Size: 855 B

View File

@ -0,0 +1,33 @@
package com.baeldung;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import com.baeldung.spring.data.redis.SpringRedisApplication;
import redis.embedded.RedisServerBuilder;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class SpringContextTest {
private static redis.embedded.RedisServer redisServer;
@BeforeClass
public static void startRedisServer() {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() {
redisServer.stop();
}
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.ReactiveKeyCommands;
import org.springframework.data.redis.connection.ReactiveStringCommands;
import org.springframework.data.redis.connection.ReactiveStringCommands.SetCommand;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServerBuilder;
import java.io.IOException;
import java.nio.ByteBuffer;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisKeyCommandsManualTest {
private static redis.embedded.RedisServer redisServer;
@Autowired
private ReactiveKeyCommands keyCommands;
@Autowired
private ReactiveStringCommands stringCommands;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Test
public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() {
Flux<String> keys = Flux.just("key1", "key2", "key3", "key4");
Flux<SetCommand> generator = keys.map(String::getBytes)
.map(ByteBuffer::wrap)
.map(key -> SetCommand.set(key)
.value(key));
StepVerifier.create(stringCommands.set(generator))
.expectNextCount(4L)
.verifyComplete();
Mono<Long> keyCount = keyCommands.keys(ByteBuffer.wrap("key*".getBytes()))
.flatMapMany(Flux::fromIterable)
.count();
StepVerifier.create(keyCount)
.expectNext(4L)
.verifyComplete();
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ReactiveListOperations;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServerBuilder;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisTemplateListOpsManualTest {
private static final String LIST_NAME = "demo_list";
private static redis.embedded.RedisServer redisServer;
@Autowired
private ReactiveStringRedisTemplate redisTemplate;
private ReactiveListOperations<String, String> reactiveListOps;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Before
public void setup() {
reactiveListOps = redisTemplate.opsForList();
}
@Test
public void givenListAndValues_whenLeftPushAndLeftPop_thenLeftPushAndLeftPop() {
Mono<Long> lPush = reactiveListOps.leftPushAll(LIST_NAME, "first", "second")
.log("Pushed");
StepVerifier.create(lPush)
.expectNext(2L)
.verifyComplete();
Mono<String> lPop = reactiveListOps.leftPop(LIST_NAME)
.log("Popped");
StepVerifier.create(lPop)
.expectNext("second")
.verifyComplete();
}
}

View File

@ -0,0 +1,93 @@
package com.baeldung.spring.data.reactive.redis.template;
import java.io.IOException;
import java.time.Duration;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import com.baeldung.spring.data.reactive.redis.model.Employee;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServerBuilder;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisTemplateValueOpsManualTest {
private static redis.embedded.RedisServer redisServer;
@Autowired
private ReactiveRedisTemplate<String, Employee> redisTemplate;
private ReactiveValueOperations<String, Employee> reactiveValueOps;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Before
public void setup() {
reactiveValueOps = redisTemplate.opsForValue();
}
@Test
public void givenEmployee_whenSet_thenSet() {
Mono<Boolean> result = reactiveValueOps.set("123", new Employee("123", "Bill", "Accounts"));
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
}
@Test
public void givenEmployeeId_whenGet_thenReturnsEmployee() {
Mono<Employee> fetchedEmployee = reactiveValueOps.get("123");
StepVerifier.create(fetchedEmployee)
.expectNext(new Employee("123", "Bill", "Accounts"))
.verifyComplete();
}
@Test
public void givenEmployee_whenSetWithExpiry_thenSetsWithExpiryTime() throws InterruptedException {
Mono<Boolean> result = reactiveValueOps.set("129", new Employee("129", "John", "Programming"), Duration.ofSeconds(1));
Mono<Employee> fetchedEmployee = reactiveValueOps.get("129");
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
Thread.sleep(2000L);
StepVerifier.create(fetchedEmployee)
.expectNextCount(0L)
.verifyComplete();
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.spring.data.redis;
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import redis.embedded.RedisServerBuilder;
import java.util.UUID;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisMessageListenerManualTest {
private static redis.embedded.RedisServer redisServer;
@Autowired
private RedisMessagePublisher redisMessagePublisher;
@BeforeClass
public static void startRedisServer() {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() {
redisServer.stop();
}
@Test
public void testOnMessage() throws Exception {
String message = "Message " + UUID.randomUUID();
redisMessagePublisher.publish(message);
Thread.sleep(1000);
assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.spring.data.redis.repo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.redis.config.RedisConfig;
import com.baeldung.spring.data.redis.model.Student;
import redis.embedded.RedisServerBuilder;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RedisConfig.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class StudentRepositoryManualTest {
@Autowired
private StudentRepository studentRepository;
private static redis.embedded.RedisServer redisServer;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Test
public void whenSavingStudent_thenAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
final Student retrievedStudent = studentRepository.findById(student.getId()).get();
assertEquals(student.getId(), retrievedStudent.getId());
}
@Test
public void whenUpdatingStudent_thenAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
student.setName("Richard Watson");
studentRepository.save(student);
final Student retrievedStudent = studentRepository.findById(student.getId()).get();
assertEquals(student.getName(), retrievedStudent.getName());
}
@Test
public void whenSavingStudents_thenAllShouldAvailableOnRetrieval() throws Exception {
final Student engStudent = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
final Student medStudent = new Student("Med2015001", "Gareth Houston", Student.Gender.MALE, 2);
studentRepository.save(engStudent);
studentRepository.save(medStudent);
List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);
assertEquals(students.size(), 2);
}
@Test
public void whenDeletingStudent_thenNotAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
studentRepository.deleteById(student.getId());
final Student retrievedStudent = studentRepository.findById(student.getId()).orElse(null);
assertNull(retrievedStudent);
}
}

22
pom.xml
View File

@ -40,13 +40,13 @@
<modules>
<module>core-java-modules</module>
<!-- <module>jackson-modules</module>-->
<!-- <module>jackson-simple</module>-->
<!-- <module>parent-java</module>-->
<!-- <module>jackson-modules</module>-->
<!-- <module>jackson-simple</module>-->
<!-- <module>parent-java</module>-->
<module>persistence-modules</module>
<module>testing-modules</module>
<module>toolkits</module>
<!-- <module>xml</module>-->
<!-- <module>xml</module>-->
</modules>
<properties>
@ -109,7 +109,7 @@
<moneta.version>1.3</moneta.version>
<jmh-core.version>1.33</jmh-core.version>
<exec-maven-plugin.version>3.0.0</exec-maven-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-surefire-plugin.version>3.0.0-M8</maven-surefire-plugin.version>
<maven-compiler-plugin.version>3.10.1</maven-compiler-plugin.version>
<logback-classic.version>1.2.5</logback-classic.version>
<rest-assured.version>3.1.1</rest-assured.version>
@ -309,6 +309,16 @@
<build>
<defaultGoal>package</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -321,7 +331,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<skipTests>true</skipTests>
</configuration>