Skip to content

Instantly share code, notes, and snippets.

@rivancic
Last active December 11, 2017 14:18
Show Gist options
  • Save rivancic/2d294d72ccedeb198e90da580925db36 to your computer and use it in GitHub Desktop.
Save rivancic/2d294d72ccedeb198e90da580925db36 to your computer and use it in GitHub Desktop.
Redis Springdata Docker

Redis

Springdata

Reference

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Client

The simplest and cleanest way to set up client is with application properties that are listed below.
Found here

spring.redis.host=aaa.bbb.ccc.ddd
spring.redis.port=eee

If for some reason this is not enough, client can be created with defining a JedisConnectionFactory @Bean.

@Bean
JedisConnectionFactory jedisConnectionFactory() {
  JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
  jedisConnectionFactory.setHostName(redisIp);
  jedisConnectionFactory.setPort(redisPort);
  return jedisConnectionFactory;
}

For any additional settings, for example how keys and values should be serialized you can create RedisTemplate<String, Object> @Bean Example below:

@Bean
@Autowired
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory connectionFactory) {
  final RedisTemplate<String, Object> template = new RedisTemplate<>();
  template.setConnectionFactory(connectionFactory);
  
  // Keys are saved and retrieved as strings
  template.setKeySerializer(new StringRedisSerializer());
  
  // In values whole object is saved so Jackson is used for transforming objects from and to string
  template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  return template;
}

Docker image

In redis.conf file settings for redis server can be set.
For example:

# Maximum memory is 100MB then start to remove keys 
maxmemory 104857600
# Remove all keys by LRU algorithm
maxmemory-policy allkeys-lru

Connect

docker exec -it [container-name] redis-cli

Queries

INFO [section]

Get info about server

RANDOMKEY

Return a random key from the currently selected database.

KEYS pattern

Returns all keys matching pattern.

Supported glob-style patterns: h?llo matches hello, hallo and hxllo h*llo matches hllo and heeeello h[ae]llo matches hello and hallo, but not hillo h[^e]llo matches hallo, hbllo, ... but not hello h[a-b]llo matches hallo and hbllo

AWS ElasticCache

Supports to deploy redis clusters: If you click on cluster then you see the endpoint to which you can connect with redis client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment