Skip to content

Integrate with Redis

Wuyi Chen edited this page Jul 3, 2019 · 12 revisions

Overview

For integrating microservices with Redis, you need to do several things:

Install Redis

Redis is an in-memory data structure project implementing a distributed, in-memory key-value database with optional durability.

Set dependencies

build.gradle

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'
}

Set configuration

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.

licensingservice.yml

# 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.

ServiceConfig.java

@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();
    }
}

Build connection

You need to add 2 bean methods in the application bootstrap class for building the connection with Redis.

Application.java

@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);
    }
}

Define and implement basic operations with Redis

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);
    }
}

Use the basic operations with Redis in your application

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);
        }
    }
}
Clone this wiki locally