-
Notifications
You must be signed in to change notification settings - Fork 59
Integrate with Redis
For integrating microservices with Redis, you need to do several things:
- Install Redis
- Set dependencies
- Set configuration
- Build connection
- Define and implement basic operations with Redis
- Use the basic operations with Redis in your application
Redis is an in-memory data structure project implementing a distributed, in-memory key-value database with optional durability.
dependencies {
compile group: 'org.springframework.data', name: 'spring-data-redis', version: '1.8.4.RELEASE'
compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
compile group: 'org.apache.commons', name: 'commons-pool2', version: '2.4.3'
}
You need to add the configuration parameters for connecting Redis. Currently, the configuration of services/server has been centralized into the config server. So you need to add 2 more parameters into the configuration YAML file of the target service which needs to integrate with Redis.
# Omit other parameters
redis.server: "127.0.0.1"
redis.port: "6379"
Also, you need to change the corresponding config class for loading those 2 new parameters into the service.
@Component
public class ServiceConfig{
// Omit other fields and methods
@Value("${redis.server}")
private String redisServer="";
@Value("${redis.port}")
private String redisPort="";
public String getRedisServer(){
return redisServer;
}
public Integer getRedisPort(){
return new Integer(redisPort).intValue();
}
}
You need to add 2 bean methods in the application bootstrap class for building the connection with Redis.
@SpringBootApplication
@RefreshScope
public class Application {
private ServiceConfig serviceConfig;
@Bean
public JedisConnectionFactory jedisConnectionFactory() { // Build the connection to Redis server
JedisConnectionFactory jedisConnFactory = new JedisConnectionFactory();
jedisConnFactory.setHostName(serviceConfig.getRedisServer());
jedisConnFactory.setPort(serviceConfig.getRedisPort());
return jedisConnFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() { // Create a RedisTemplate object for executing operations with Redis
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Like Spring Data JPA, you need to create an interface to define the basic operations with Redis.
OrganizationRedisRepository.java
public interface OrganizationRedisRepository {
void saveOrganization(Organization org); // Add a new organization record to Redis
void updateOrganization(Organization org); // Update a organization record in Redis
void deleteOrganization(String orgId); // Delete a organization record by the organization ID from Redis
Organization findOrganization(String orgId); // Search a organization record by the organization ID
}
After that, you need to create a concrete class for implementing the basic operations defined in the interface.
OrganizationRedisRepositoryImpl.java
@Repository
public class OrganizationRedisRepositoryImpl implements OrganizationRedisRepository {
private static final String HASH_NAME = "organization";
private RedisTemplate<String, Object> redisTemplate;
private HashOperations<String, String, Object> hashOperations;
public OrganizationRedisRepositoryImpl(){
super();
}
@Autowired
private OrganizationRedisRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@PostConstruct
private void init() {
hashOperations = redisTemplate.opsForHash();
}
@Override
public void saveOrganization(Organization org) {
hashOperations.put(HASH_NAME, org.getId(), org);
}
@Override
public void updateOrganization(Organization org) {
hashOperations.put(HASH_NAME, org.getId(), org);
}
@Override
public void deleteOrganization(String organizationId) {
hashOperations.delete(HASH_NAME, organizationId);
}
@Override
public Organization findOrganization(String organizationId) {
return (Organization) hashOperations.get(HASH_NAME, organizationId);
}
}
After setting up the integration with Redis, you can use the interface of the Redis operations directly by using the @Autowired
annotation.
OrganizationRestTemplateClient
@Component
public class OrganizationRestTemplateClient {
@Autowired
OrganizationRedisRepository orgRedisRepo; // With @Autowired, the `OrganizationRedisRepositoryImpl` will be injected in here automatically
/* Omit other fields and methods */
private Organization checkRedisCache(String organizationId) {
try {
return orgRedisRepo.findOrganization(organizationId); // Use the Redis operations
} catch (Exception ex){
logger.error("Error encountered while trying to retrieve organization {} check Redis Cache. Exception {}", organizationId, ex);
return null;
}
}
private void cacheOrganizationObject(Organization org) {
try {
orgRedisRepo.saveOrganization(org); // Use the Redis operations
} catch (Exception ex){
logger.error("Unable to cache organization {} in Redis. Exception {}", org.getId(), ex);
}
}
}
- Overview
- Getting Started
-
Technical Essentials
- Autowired
- SpringData JPA
- Configuration File Auto-loading
- Configuration Encryption
- Service Discovery with Eureka
- Resiliency Patterns with Hystrix
- Configure Hystrix
- Service Gateway with Zuul
- Zuul Filters
- Protect Service with Spring Security and OAuth2
- Use JWT as Access Token
- Store Clients and Users' Credentials to DB
- Integrate with Message Queue (Kafka)
- Integrate with Redis
- Tune Logging
- Log Aggregation
- Send Trace to Zipkin
- Build Runnable Jar
- Core Application Logic
- Components