在springboot1.x中默认使用Jedis,而在springboot2.x中默认使用lettuce。
为什么使用lettuce替换jedis呢?
Jedis在实现上是直连的redis server,在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接;
Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,因为StatefulRedisConnection是线程安全的,所以一个连接实例就可以满足多线程环境下的并发访问;
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
2)application.properties配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123
spring.redis.lettuce.pool.max-active=500
spring.redis.lettuce.pool.max-idle=300
spring.redis.lettuce.pool.max-wait=1000
spring.redis.lettuce.pool.min-idle=0
spring.redis.database=8
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory, RedisSerializer
import com.kevin.core.result.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
/**
* @author kevin
* @create 2020/8/7 14:42
*/
@ApiResult
@RestController
public class TestController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping(value="/test",produces= MediaType.APPLICATION_JSON_VALUE)
public Object test(){
Map user=new HashMap<>();
user.put("id", 1);
user.put("name","kevin");
user.put("createTime", LocalDateTime.now());
redisTemplate.opsForValue().set("user:"+user.get("id"), user);
return redisTemplate.opsForValue().get("user:"+user.get("id"));
}
}
org.springframework.boot
spring-boot-starter-data-redis
io.lettuce
lettuce-core
redis.clients
jedis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123
spring.redis.jedis.pool.max-active=500
spring.redis.jedis.pool.max-idle=300
spring.redis.jedis.pool.max-wait=1000
spring.redis.jedis.pool.min-idle=0
spring.redis.database=8