下载实例源码
使用步骤
1、引入 spring-boot-starter-data-redis 依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在 application.yml 配置 Redis 的信息
spring:redis:host: 127.0.0.1port: 6379password: 123456database: 0 # 几号库lettuce:pool:max-active: 8 # 最大连接max-idle: 8 # 最大空闲连接min-idle: 0 # 最小空闲连接max-wait: 100ms # 连接等待时间
3、注入 RedisTemplate
@Autowired
private RedisTemplate redisTemplate;
Demo1
package com.test;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.junit4.SpringRunner;import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDemoApplicationTest {// 注入 RedisTemplate@Autowiredprivate RedisTemplate redisTemplate;// String 类型@Testpublic void testString () {redisTemplate.opsForValue().set("name", "xiaobai");Object name = redisTemplate.opsForValue().get("name");System.out.println(name);}// Hash 类型@Testpublic void testHash () {redisTemplate.opsForHash().put("user1", "name", "clarence");redisTemplate.opsForHash().put("user1", "age", "25");Map map = redisTemplate.opsForHash().entries("user1");System.out.println(map);}// List 类型@Testpublic void testList () {redisTemplate.opsForList().leftPushAll("names", "xiaobai", "xiaohei", "xiaolan");List<String> names = redisTemplate.opsForList().range("names", 0, 3);System.out.println(names);}// Set 类型@Testpublic void testSet () {redisTemplate.opsForSet().add("set", "a", "b", "c");Set<String> set = redisTemplate.opsForSet().members("set");System.out.println(set);}// SortedSet 类型@Testpublic void testSortedSet () {redisTemplate.opsForZSet().add("class", "xiaobai", 90);Set aClass = redisTemplate.opsForZSet().rangeByScore("class", 90, 100);System.out.println(aClass);Set<ZSetOperations.TypedTuple<String>> set = new HashSet<>();set.add(new DefaultTypedTuple<>("xiaohei", 88.0));set.add(new DefaultTypedTuple<>("xiaohui", 94.0));set.add(new DefaultTypedTuple<>("xiaolan", 84.0));set.add(new DefaultTypedTuple<>("xiaolv", 82.0));set.add(new DefaultTypedTuple<>("xiaohong", 99.0));redisTemplate.opsForZSet().add("class", set);Set aClass1 = redisTemplate.opsForZSet().range("class", 0, 6);System.out.println(aClass1);}
}
序列化
1、默认是 JdkSerializationRedisSerializer
RedisTemplate 可以接收任意 Object 作为值写入 Redis,不过在写入前会把 Object 序列化为字节形式,默认是采用 JDK 序列化,上面的 demo 运行后得到的结果如下:
缺点:可读性差;内存占用较大
2、添加配置文件,使用 String 序列化、Json 序列化
Redis 配置文件
package com.test.config;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.RedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {// 创建 RedisTemplate 对象RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();// 设置连接工厂redisTemplate.setConnectionFactory(connectionFactory);// 设置 Key 的序列化 - String 序列化 RedisSerializer.string() => StringRedisSerializer.UTF_8redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());// 设置 Value 的序列化 - JSON 序列化 RedisSerializer.json() => GenericJackson2JsonRedisSerializerredisTemplate.setValueSerializer(RedisSerializer.json());redisTemplate.setHashValueSerializer(RedisSerializer.json());// 返回return redisTemplate;}
}
引入 Jackson 依赖
<!--Jackson依赖-->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.11.4</version>
</dependency>
添加 User 实体类
package com.test.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private String name;private Integer age;
}
注意这里要安装lombok插件,同时引入lombok依赖
Demo2
package com.test;import com.test.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.junit4.SpringRunner;import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDemoApplicationTest2 {// 注入 RedisTemplate@Autowiredprivate RedisTemplate redisTemplate;// String 类型@Testpublic void testString () {redisTemplate.opsForValue().set("name", "xiaobai");Object name = redisTemplate.opsForValue().get("name");System.out.println(name);}@Testpublic void testSaveUser() {redisTemplate.opsForValue().set("user", new User("小白", 23));User user = (User) redisTemplate.opsForValue().get("user");System.out.println(user);}
}
运行结果
StringRedisTemplate
从上述 Demo 的运行结果可以看到,为了在反序列化时知道对象的类型,Json 序列化会将类的 class 类型写入 json 结果中存入 Redis,会带来额外的内存开销
为了节省内存空间,我们并不会使用 json 序列化器来处理 value,而是统一使用 String 序列化器,要求只能存储 String 类型的 key 和 value。当需要存储 Java 对象时,手动完成对象的序列化和反序列化
spring 提供了一个 StringRedisTemplate 类,其 key 和 value 的序列化方式默认为 String 方式
引入 fastjson 依赖
<!--fastjson依赖-->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version>
</dependency>
运行结果