Java 中使用 RedisTemplate 操作 Redis

2021-10-20 11:15:17
添加依赖 pom.xml ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 配置类 ``` import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.cache.annotation.CachingConfigurerSupport; 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.*; import org.springframework.data.redis.serializer.*; @Configuration public class RedisConfig extends CachingConfigurerSupport { /** * RedisTemplate 默认配置的是使用 Java JDK 的序列化,如果是对象,在Redis里查看时不直观 * key 使用 String, value 列序列化 json */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 连接工厂 template.setConnectionFactory(factory); // key 使用 StringRedisSerializer 来序列化 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); template.setKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); // value 采用 json 序列化 Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = jsonSerializer(); template.setValueSerializer(jsonRedisSerializer); template.setHashValueSerializer(jsonRedisSerializer); template.afterPropertiesSet(); return template; } /** * 序列化器 */ private Jackson2JsonRedisSerializer<Object> jsonSerializer() { Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); // 对象映射 ObjectMapper om = new ObjectMapper(); // 序列化所有字段和修饰符范围 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 将类名序列化到json中 {"@class":"model.User", "id":"1", "name":"hello"} // 否则不能反序列化 {"id":"1", "name":"hello"} om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jsonRedisSerializer.setObjectMapper(om); return jsonRedisSerializer; } } ``` 数据操作示例 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class TestController { @Autowired private RedisTemplate<String, Object> redisTemplate; @GetMapping("/test") public String test() { // string redisTemplate.opsForValue().set("foo", "hello"); redisTemplate.opsForValue().set("bar", 100); String foo = (String) redisTemplate.opsForValue().get("foo"); System.out.println(foo); // hello String noData = (String) redisTemplate.opsForValue().get("noData"); System.out.println(noData); // null redisTemplate.opsForValue().increment("bar"); int bar2 = (int) redisTemplate.opsForValue().get("bar"); // 101 System.out.println(bar2); // hash User user = new User(3, "Jack"); redisTemplate.opsForValue().set("user1", user); User obj = (User) redisTemplate.opsForValue().get("obj"); System.out.println(obj); Map<String, Object> map = new HashMap<>(); map.put("name", "Mary"); map.put("age", 18); redisTemplate.opsForHash().putAll("user2", map); Map<Object, Object> user3 = redisTemplate.opsForHash().entries("user2"); System.out.println(user3); // list redisTemplate.opsForList().leftPush("names", "jack"); redisTemplate.opsForList().leftPush("names", "mary"); redisTemplate.opsForList().leftPush("names", "lily"); System.out.println(redisTemplate.opsForList().rightPop("names")); // jack System.out.println(redisTemplate.opsForList().rightPop("names")); // mary System.out.println(redisTemplate.opsForList().rightPop("names")); // lily System.out.println(redisTemplate.opsForList().rightPop("names")); // null return "ok"; } public static class User { private int id; private String name; public User() { } public User(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ``` 连接配置信息 ``` # Redis服务器地址 (默认127.0.0.1) spring.redis.host=127.0.0.1 # Redis服务器连接端口 (默认6379) spring.redis.port=6379 # Redis数据库索引 (默认为0) spring.redis.database=0 # Redis服务器连接密码 (默认为空) spring.redis.password= ```