@Test
public void testRedis() {
// 多线程访问相同key
for (int i = 0; i < 10; i++) {
int finalI = i;
new Thread(() -> {
// 不存在,则set
stringRedisTemplate.opsForValue().setIfAbsent("key:1", "1");
}, i+"").start();
}
}
报错如下:
org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379
redis并发多线程连接报超时异常,不能使用lettuce连接池,改用jedis连接池,修改如下:
org.springframework.boot
spring-boot-starter-data-redis
lettuce-core
io.lettuce
org.apache.commons
commons-pool2
redis.clients
jedis
spring
#redis相关配置
redis:
# 指定库,默认0库,全部16个库
database: 3
# 配置redis的主机地址,需要修改成自己的
host: localhost
port: 6379
password:
timeout: 5000
jedis:
pool:
# 连接池中的最大空闲连接,默认值也是8。
max-idle: 500
# 连接池中的最小空闲连接,默认值也是0。
min-idle: 50
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)
max-active: 1000
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
max-wait: 2000
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.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(jedisConnectionFactory);
return redisTemplate;
}
}



