(代码篇)java, spring整合redis最详解析
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
@Bean
JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(10);
config.setMaxTotal(50);
config.setMinIdle(1);
return config;
}
@Bean
JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig poolConfig) {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
factory.setPoolConfig(poolConfig);
// 设置 Redis 服务器地址
factory.setHostName("localhost");
// 设置 Redis 服务器连接端口
factory.setPort(6379);
return factory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(JedisConnectionFactory jedisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(jedisConnectionFactory);
return template;
}
}
这段代码定义了一个配置类RedisConfig
,其中包含了创建JedisPoolConfig
、JedisConnectionFactory
以及RedisTemplate<String, Object>
和StringRedisTemplate
的方法。这些bean可以被Spring应用上下文所管理,并用于操作Redis数据库。
评论已关闭