Redis With SpringBoot
To setup Redis with SpringBoot, we need a configuration class
package java_redis_db.config;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
@Setter
@Configuration
@ConfigurationProperties(prefix = "redis")
@EnableRedisRepositories(basePackages = "java_redis_db.repositories.redis")
public class RedisConfig {
private String url;
private int port;
@Bean
public JedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(url, port);
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
In here we have @Setter
and @ConfigurationProperties
for Spring to load in the properties of configuration file. In which our application.yml
can have something like this:
redis:
url: localhost
port: 6379
Optional: For intellij to understand this configuration, we can add additional-spring-configuration-metadata.json
{
"properties": [
{
"name": "redis.port",
"type": "java.lang.String",
"description": "Description for redis.port."
},
{
"name": "redis.url",
"type": "java.lang.String",
"description": "Description for redis.url."
}
]
}
@EnableRedisRepositories(basePackages = "java_redis_db.repositories.redis")
to declare our RedisRepository inside that package.
[!note]
It's important to declare the base package and separate packages betweenJPA
andRedis
to avoid confliction.For example in this project i have everything
JPA
related is located inpackage java_redis_db.repositories.jpa;
whereas for redis it ispackage java_redis_db.repositories.redis;
redisConnectionFactory
to set the connection and redisTemplate
to convert from redis data to Java class.
package java_redis_db.repositories.redis;
import java_redis_db.entities.Customer;
import org.springframework.data.repository.CrudRepository;
public interface RedisCustomerRepository extends CrudRepository<Customer, Long> {
}
And we can just use it like
@RequiredArgsConstructor
@Service
public class MyService {
final RedisCustomerRepository redisCustomerRepository;
public void doSomething() {
redisCustomerRepository.save(new Customer())
redisCustomerRepository.findById(id);
}
}
This is how redis stores in our entity: