Spring RedisTemplate with Pure Annotation Configuration: Complete Tutorial

This tutorial demonstrates configuring Spring Data RedisTemplate using pure Java annotations, covering Maven dependencies, connection pooling, serialization, and CRUD operations for String, List, Hash, Set, and Sorted Set data types with complete code examples.

Java Captain
Java Captain
Java Captain
Spring RedisTemplate with Pure Annotation Configuration: Complete Tutorial

Introduction: Jedis vs RedisTemplate

The article begins by comparing Jedis and RedisTemplate. Jedis is the official Redis Java client, while RedisTemplate is Spring's high-level abstraction over Jedis API. RedisTemplate provides automatic connection pool management and is more convenient for most development scenarios.

Project Setup with Maven Dependencies

A Maven project is created with the following key dependencies (tested stable versions):

<dependencies>
  <!-- Spring dependencies -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.17</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.17</version>
  </dependency>
  <!-- JUnit -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
  </dependency>
  <!-- Redis dependencies -->
  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.0.6.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
  </dependency>
  <!-- Logging (optional but avoids console warnings) -->
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.21</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  </dependency>
</dependencies>

After adding dependencies, refresh Maven to download jars. The project structure includes com.jobs.config for Spring configuration classes and resources for property files.

Configuration Files

redis.properties

redis.host=localhost
redis.port=6379
# redis.password=123456
redis.maxActive=10
redis.maxIdle=5
redis.minIdle=1
redis.maxWait=3000

log4j.properties

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

RedisConfig Class: Annotation-Based Bean Definitions

The RedisConfig class uses @PropertySource("redis.properties") and defines four @Bean methods:

getRedisTemplate : Creates RedisTemplate, sets connection factory, and critically configures StringRedisSerializer for keys and hash keys to avoid JDK serialization garbage characters.

getRedisConnectionFactory : Builds JedisConnectionFactory using RedisStandaloneConfiguration and a pooled JedisClientConfiguration.

getGenericObjectPoolConfig : Configures Apache Commons Pool2 GenericObjectPoolConfig with values from properties (maxTotal, minIdle, maxIdle, maxWaitMillis).

getRedisStandaloneConfiguration : Sets host and port from properties; password commented out.

@PropertySource("redis.properties")
public class RedisConfig {
  @Value("${redis.host}")
  private String host;
  @Value("${redis.port}")
  private Integer port;
  @Value("${redis.maxActive}")
  private Integer maxActive;
  @Value("${redis.minIdle}")
  private Integer minIdle;
  @Value("${redis.maxIdle}")
  private Integer maxIdle;
  @Value("${redis.maxWait}")
  private Integer maxWait;

  @Bean
  public RedisTemplate getRedisTemplate(@Autowired RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate redisTemplate = new RedisTemplate();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    RedisSerializer stringSerializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(stringSerializer);
    redisTemplate.setHashKeySerializer(stringSerializer);
    return redisTemplate;
  }

  @Bean
  public RedisConnectionFactory getRedisConnectionFactory(
      @Autowired RedisStandaloneConfiguration redisStandaloneConfiguration,
      @Autowired GenericObjectPoolConfig genericObjectPoolConfig) {
    JedisClientConfiguration.JedisPoolingClientConfigurationBuilder builder =
        (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
    builder.poolConfig(genericObjectPoolConfig);
    return new JedisConnectionFactory(redisStandaloneConfiguration, builder.build());
  }

  @Bean
  public GenericObjectPoolConfig getGenericObjectPoolConfig() {
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(maxActive);
    config.setMinIdle(minIdle);
    config.setMaxIdle(maxIdle);
    config.setMaxWaitMillis(maxWait);
    return config;
  }

  @Bean
  public RedisStandaloneConfiguration getRedisStandaloneConfiguration() {
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
    config.setHostName(host);
    config.setPort(port);
    // config.setPassword(RedisPassword.of(password));
    return config;
  }
}

SpringConfig: Bootstrap Configuration

@Configuration
@ComponentScan("com.jobs")
@Import(RedisConfig.class)
public class SpringConfig {}

Redis Operations Demonstration via JUnit Tests

The RedisTest class uses @RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(classes = SpringConfig.class) to load the Spring context. It autowires RedisTemplate and provides test methods for each Redis data type.

String Operations

@Test
public void testString() {
  redisTemplate.opsForValue().set("name", "候胖胖");
  redisTemplate.opsForValue().set("age", "40");
  String name = redisTemplate.opsForValue().get("name").toString();
  String age = redisTemplate.opsForValue().get("age").toString();
  System.out.println("name:" + name + ",age:" + age);
}

List Operations (used as queue)

@Test
public void testList() {
  redisTemplate.opsForList().rightPush("fat", "任肥肥");
  redisTemplate.opsForList().rightPush("fat", "侯胖胖");
  redisTemplate.opsForList().rightPush("fat", "李墩墩");
  long fatCount = redisTemplate.opsForList().size("fat");
  System.out.println("列表数量:" + fatCount);
  for (int i = 0; i < fatCount; i++) {
    String fatMan = redisTemplate.opsForList().leftPop("fat").toString();
    System.out.println(fatMan);
  }
}

Hash Operations (suitable for objects)

@Test
public void testHash() {
  Map<String, String> user1 = new HashMap<>();
  user1.put("name", "侯胖胖");
  user1.put("age", "40");
  user1.put("kg", "80");
  Map<String, String> user2 = new HashMap<>();
  user2.put("name", "任肥肥");
  user2.put("age", "38");
  user2.put("kg", "90");
  redisTemplate.opsForHash().putAll("user1", user1);
  redisTemplate.opsForHash().putAll("user2", user2);
  redisTemplate.opsForHash().put("user1", "age", "45");
  redisTemplate.opsForHash().put("user2", "kg", "100");
  Map<String, String> user111 = redisTemplate.opsForHash().entries("user1");
  Map<String, String> user222 = redisTemplate.opsForHash().entries("user2");
  System.out.println(user111);
  System.out.println(user222);
}

Set Operations (intersection, union, difference)

@Test
public void testSet() {
  redisTemplate.opsForSet().add("aaa", "a", "b", "c", "x", "y", "z", "a", "x");
  redisTemplate.opsForSet().add("bbb", "b", "c", "d", "e", "f", "y", "b", "e");
  Set<String> sinter = redisTemplate.opsForSet().intersect("aaa", "bbb");
  System.out.println("交集:" + sinter);
  Set<String> sunion = redisTemplate.opsForSet().union("aaa", "bbb");
  System.out.println("并集:" + sunion);
  Set<String> sdiff = redisTemplate.opsForSet().difference("aaa", "bbb");
  System.out.println("aaa 相对于 bbb 的差集:" + sdiff);
}

Sorted Set (ZSet) Operations (leaderboard use case)

@Test
public void testZset() {
  redisTemplate.opsForZSet().add("vote", "侯胖胖", 10d);
  redisTemplate.opsForZSet().add("vote", "李墩墩", 7d);
  redisTemplate.opsForZSet().add("vote", "任肥肥", 6d);
  redisTemplate.opsForZSet().add("vote", "乔豆豆", 12d);
  redisTemplate.opsForZSet().add("vote", "杨重重", 8d);
  redisTemplate.opsForZSet().add("vote", "任肥肥", 9d); // update score
  Set<String> vote1 = redisTemplate.opsForZSet().range("vote", 0, -1);
  System.out.println("投票数量升序排列:" + vote1);
  Set<String> vote2 = redisTemplate.opsForZSet().reverseRange("vote", 0, 2);
  System.out.println("投票数量倒序前 3 个人:" + vote2);
}

Conclusion

The article demonstrates a complete, working example of Spring Data Redis with pure annotation configuration. It covers project setup, connection pooling, key serialization best practices, and practical CRUD operations for all core Redis data structures. For further details, refer to the Spring Data Redis official documentation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaRedisSerializationSpringSpring Data RedisConnection PoolingAnnotation ConfigurationRedisTemplate
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.