0

I have the following two bean definitions for Spring Data Redis. I cant seem to find the relevant documentation to determine the scopes(singleton,request or session) of these beans for a web app.

@Bean
public StringRedisTemplate redisTemplate() throws Exception {
    StringRedisTemplate redisTemplate = new StringRedisTemplate();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    return redisTemplate;
}

@Bean
public StringRedisConnection stringRedisConnection() throws Exception {
    return new DefaultStringRedisConnection(redisTemplate().getConnectionFactory().getConnection());
}
Shivam Sinha
  • 4,924
  • 7
  • 43
  • 65
  • unless combined with `@Scope` those will be singletons. Would mit make sense in you case to use a `StringRedisTemplate` using eg. the `jedisConnectionFactory` instead of the `StringRedisConnection`? – Christoph Strobl Jun 18 '15 at 11:29
  • Hi Chris - I was to use the zrangelex function which is only available from the StringRedisConnection. https://jira.spring.io/browse/DATAREDIS-378. To clarify I am asking should I initialize a new StringRedisConnection per request/session from a user or is it fine for it to just be a singleton. Thanks – Shivam Sinha Jun 19 '15 at 01:15
  • 1
    I would go for using `RedisTemplate.execute` with a `RedisCallback` so you can issue `zRangeByLex` from there and do not have to worry about the connection stuff. I also created [DATAREDIS-407](https://jira.spring.io/browse/DATAREDIS-407) for adding the command to `ZSetOperations` so that it's available via `RedisTemplate.opsForZSet`. – Christoph Strobl Jun 19 '15 at 06:12
  • Thanks @ChristophStrobl – Shivam Sinha Jun 24 '15 at 03:07

1 Answers1

0

Thanks to @Christoph Strobl recommendation here is the implementation Iam currently using

  public  List<String> testAutoComplete(String key,String query, int limitCount){
        StringRedisSerializer serializer = new StringRedisSerializer();
        RedisZSetCommands.Range range = Range.range();
        range.gt(query);
        RedisZSetCommands.Limit limit = new RedisZSetCommands.Limit();
        limit.count(limitCount);
       return template.execute(new RedisCallback< List<String>>() {
            public  List<String> doInRedis(RedisConnection connection) {
                Set<byte[]> results = connection.zRangeByLex(serializer.serialize(key), range,limit);
                List<String> resultAsString = new ArrayList<String>();
                for(byte[] result : results){
                    resultAsString.add(serializer.deserialize(result));
                }
                return resultAsString;
            }
        },false); 
    }
Shivam Sinha
  • 4,924
  • 7
  • 43
  • 65