springboot 使用的是2.2 redis 使用的版本是3.0下面是相关的代码
pom的依赖如下 :
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
然后的配置文件如下:
server: port: 9015 spring: redis: database: 0 host: localhost port: 6379 password: lettuce: pool: min-idle: 0 max-idle: 8 max-wait: -1m max-active: 20
使用的实体类如下:
import lombok.Data; import java.io.Serializable; @Data public class User implements Serializable { private int id ; private String name; private int age; }
配置类如下:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) { RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; } }
调用redis的操作类如下:
import com.ext.demolettuce.entity.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.Serializable; @RestController public class testController { private Logger logger = LoggerFactory.getLogger(testController.class); @Autowired private RedisTemplate<String, Serializable> template; @RequestMapping("/get1") public String getOne(){ String key = "user:1"; User user = new User(); user.setId(1); user.setName("aa"); user.setAge(11); template.opsForValue().set(key, user); User user1 = (User) template.opsForValue().get(key); logger.info("--------------------uesr: "+user1.toString()); return "success"; } }
要注意的是 使用lettuce的时候必须要加 commons-pool2 这个依赖,否则会出现连接错误。
欢迎批评指正