基於lettuce連接池方式集成
1.添加pom.xml文件
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!– 1.5的版本默認採用的連接池技術是jedis,2.0以上版本默認連接池是lettuce, 因爲此次是採用jedis,所以需要排除lettuce的jar –>
<exclusions>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!– jedis客戶端 –>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--spring2.X集成redis所需common-pool2,使用jedis必須依賴它-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2.application.properties文件 配置(可配置也可不配置)
#redis配置開始
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=localhost
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認爲空)
spring.redis.password=
#jedis連接池
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=1024
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=10000
# 連接池中的最大空閒連接
spring.redis.jedis.pool.max-idle=200
# 連接池中的最小空閒連接
spring.redis.jedis.pool.min-idle=0
#lettuce連接池
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.lettuce.pool.max-active=1024
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.lettuce.pool.max-wait=10000
# 連接池中的最大空閒連接
spring.redis.lettuce.pool.max-idle=200
# 連接池中的最小空閒連接
spring.redis.lettuce.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=10000
#redis配置結束
spring.redis.block-when-exhausted=true
3.配置RedisConfig —配完這個就可以用了
@Configuration
@EnableCaching
public class RedisConfig {
/**
* RedisTemplate配置
* @param connectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());//key序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
4.調用的時候還用一個坑,在調用的時候必須用@Resource這個註解,用@Autowired會報錯,我看見好多的文章都是用Autowired,也不知道是我的問題還是別人的問題,有發現還請告知
@Resource(name = "redisTemplate")
private RedisTemplate redisTemplate;
希望這篇文章希望能幫得到你。