Необходимо настроить Spring для использования Redis
и использовать RedisTemplate
при использовании spring-data-redis
. Использование шаблона обеспечивает простую настройку и позволяет быстро настроить и использовать redis в приложениях Spring.
Вот как должна выглядеть конфигурация, если вы используете конфигурации на основе аннотаций
package test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@ComponentScan("test") // Component Scan Base Package
public class RedisConfiguration{
// Better if you can use a properties file and inject these values
private String redisHost = "localhost";
private int redisPort = 6379;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisHost);
factory.setPort(redisPort);
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate< String, Object > redisTemplate() {
final RedisTemplate< String, Object > template = new RedisTemplate< String, Object >();
template.setConnectionFactory( jedisConnectionFactory() );
template.setKeySerializer( new StringRedisSerializer() );
template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
return template;
}
}
А затем используйте в рамках услуги
@Service
public class RedisService {
@Autowired
private RedisTemplate< String, Object > template;
// Methods to add and get objects from redis goes here
}
И, наконец, основной класс,
public class MainClassTest{
public static void main(String... args) throws InterruptedException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfiguration.class);
RedisService redisService = context.getBean(RedisService.class);
// Use the service here
}
}