添加依赖
<!-- Redis 依赖 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.1</version> </dependency> <!-- spring data redis 依赖使用 1+最新版本因为 2+需要 spring5+版本 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.8.18.RELEASE</version> </dependency>
添加 applicationContext-redis.xml 配置文件
<!-- 连接池配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大连接数 --> <property name="maxTotal" value="1024"/> <!-- 最大 空闲连接数 --> <property name="maxIdle" value="200"/> <!-- 获取连接时最大等待毫秒数 --> <property name="maxWaitMillis" value="10000"/> <!-- 在获取连接时检查有效性 --> <property name="testOnBorrow" value="true"/> </bean> <!-- 客户端连接工厂 --> <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true" p:host-name="192.168.75.163" p:port="6379" > <!-- 连接池引用 --> <constructor-arg name="poolConfig" ref="jedisPoolConfig"/> </bean> <!-- redisTemplate 配置 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory"> <!-- 配置序列化操作 --> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> </bean>
测试环境是否搭建成功
4.1、 操作 String
@Autowired private RedisTemplate<String, Object> redisTemplate; /** * redisTemplate.opsForValue() -> ValueOperations<String, Object>;// 操作字符串 * redisTemplate.opsForHash() -> HashOperations<String, String, String>;// 操作 hash * redisTemplate.opsForList() -> ListOperations<String, Object>;// 操作 list * redisTemplate.opsForSet() -> SetOperations<String, Object>;// 操作 set * redisTemplate.opsForZSet() -> ZSetOperations<String, Object>;// 操作 SortedSet */ // 1.操作 String @Test public void testString() { ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue(); // 添加一条数据 valueOperations.set("username", "zhangsan"); valueOperations.set("age", "18"); // redis 中以层级关系、目录形式存储数据 valueOperations.set("user:01", "lisi"); valueOperations.set("user:02", "wangwu"); // 添加多条数据 Map<String, String> userMap = new HashMap<>(); userMap.put("address", "bj"); userMap.put("sex", "1"); valueOperations.multiSet(userMap); // 获取一条数据 Object username = valueOperations.get("username"); System.out.println(username); // 获取多条数据 List<String> keys = new ArrayList<>(); keys.add("username"); keys.add("age"); keys.add("address"); keys.add("sex"); List<Object> resultList = valueOperations.multiGet(keys); for (Object str : resultList) { System.out.println(str); } // 删除 //redisTemplate.delete("username"); }
看下结果
操作 hash
@Test public void testHash() { HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash(); /* * 添加一条数据 * 参数一:redis 的 key * 参数二:hash 的 key * 参数三:hash 的 value */ hashOperations.put("userInfo","name","lisi"); // 添加多条数据 Map<String, String> map = new HashMap(); map.put("age", "20"); map.put("sex", "1"); hashOperations.putAll("userInfo", map); // 获取一条数据 String name = hashOperations.get("userInfo", "name"); System.out.println(name);//lisi // 获取多条数据 List<String> keys = new ArrayList<>(); keys.add("age"); keys.add("sex"); List<String> resultlist =hashOperations.multiGet("userInfo", keys); for (String str : resultlist) { System.out.println(str); } // 获取 Hash 类型所有的数据 Map<String, String> userMap = hashOperations.entries("userInfo"); for (Map.Entry<String, String> userInfo : userMap.entrySet()) { System.out.println(userInfo.getKey() + "--" + userInfo.getValue()); } // 删除 用于删除 hash 类型数据 //hashOperations.delete("userInfo", "name"); }
看下结果
操作 list
@Test public void testList() { ListOperations<String, Object> listOperations = redisTemplate.opsForList(); // 左添加(上) listOperations.leftPush("students", "Wang Wu"); listOperations.leftPush("students", "Li Si"); // 左添加(上) 把 value 值放到 key 对应列表中 pivot 值的左面,如果 pivot 值存在的话 listOperations.leftPush("students", "Wang Wu", "Li Si"); // 右添加(下) listOperations.rightPush("students", "Zhao Liu"); // 获取 start 起始下标 end 结束下标 包含关系 List<Object> students = listOperations.range("students", 0,2); for (Object stu : students) { System.out.println(stu); } // 根据下标获取 Object stu = listOperations.index("students", 1); System.out.println(stu); // 获取总条数 Long total = listOperations.size("students"); System.out.println("总条数:" + total); // 删除单条 删除列表中存储的列表中几个出现的 Li Si。 //listOperations.remove("students", 1, "Li Si"); // 删除多条 //redisTemplate.delete("students"); }
看下结果
操作 set
@Test public void testSet() { SetOperations<String, Object> setOperations = redisTemplate.opsForSet(); // 添加数据 String[] letters = new String[]{"aaa", "bbb", "ccc", "ddd", "eee"}; //setOperations.add("letters", "aaa", "bbb", "ccc", "ddd", "eee"); setOperations.add("letters", letters); // 获取数据 Set<Object> let = setOperations.members("letters"); for (Object letter: let) { System.out.println(letter); } // 删除 //setOperations.remove("letters", "aaa", "bbb"); }
看下结果
操作 sorted set
@Test public void testSortedSet() { ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet(); ZSetOperations.TypedTuple<Object> objectTypedTuple1 = new DefaultTypedTuple<>("zhangsan", 99D); ZSetOperations.TypedTuple<Object> objectTypedTuple2 = new DefaultTypedTuple<>("lisi", 96D); ZSetOperations.TypedTuple<Object> objectTypedTuple3 = new DefaultTypedTuple<>("wangwu", 92D); ZSetOperations.TypedTuple<Object> objectTypedTuple4 = new DefaultTypedTuple<>("zhaoliu", 100D); ZSetOperations.TypedTuple<Object> objectTypedTuple5 = new DefaultTypedTuple<>("tianqi", 95D); Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>(); tuples.add(objectTypedTuple1); tuples.add(objectTypedTuple2); tuples.add(objectTypedTuple3); tuples.add(objectTypedTuple4); tuples.add(objectTypedTuple5); // 添加数据 zSetOperations.add("score", tuples); // 获取数据 Set<Object> scores = zSetOperations.range("score", 0, 4); for (Object score: scores) { System.out.println(score); } // 获取总条数 Long total = zSetOperations.size("score"); System.out.println("总条数:" + total); // 删除 //zSetOperations.remove("score", "zhangsan", "lisi"); }
看下结果
获取所有 key&删除
// 获取所有 key @Test public void testAllKeys() { // 当前库 key 的名称 Set<String> keys = redisTemplate.keys("*"); for (String key: keys) { System.out.println(key); } } // 删除 @Test public void testDelete() { // 删除 通用 适用于所有数据类型 redisTemplate.delete("score"); }
看下结果
public User doQueryUserById(Integer userId) {
// 先从 Redis 查询
User user = (User) redisTemplate.opsForValue().get("user:id_" + userId);
if(null != user){
return user;
}
// Redis 没有再从 mysql 查询
user = userDao.queryUserById(userId);
if(null != user){
redisTemplate.opsForValue().set("user:id_" + userId, user);
return user;
}
return null;
}
public User doQueryUserById2Json(Integer userId) {
// 先从 Redis 查询
Object jsonUser = redisTemplate.opsForValue().get("user:id_" + userId);
User user = null;
if(null != user){
user = JsonUtil.jsonStr2Object((String) jsonUser, User.class);
return user;
}
// Redis 没有再从 mysql 查询
user = userDao.queryUserById(userId);
if(null != user){
redisTemplate.opsForValue().set("user:id_" + userId, JsonUtil.object2JsonStr(user));
return user;
}
return null;
}
问题:如果要直接保存 Bean 对象到 Redis,该如何操作?
1、配置文件不能配置序列化操作
a. 配置文件不能配置序列化操作,否则会报错。 java.lang.ClassCastException: com.shsxt.entity.User cannot be cast to java.lang.String
b. Bean 实体必须实现序列化接口
c. 实现方式
public User queryUserById(Integer userId) { // 先从 Redis 查询 User user = (User) redisTemplate.opsForValue().get("user:id_" + userId); if(null != user){ return user; } // Redis 没有再从 mysql 查询 user = userDao.queryUserById(userId); if(null != user){ redisTemplate.opsForValue().set("user:id_" + userId, user); return user; } return null; }
d. Redis Windows 客户端看到的数据不友好
2、配置文件配置序列化操作
a. 配置文件配置序列化操作
b. Bean 实体需要转成 json 格式字符串
c. 实现方式
public User queryUserById(Integer userId) { // 先从 Redis 查询 Object jsonUser = redisTemplate.opsForValue().get("user:id_" + userId); User user = null; if(null != user){ user = JsonUtil.jsonStr2Object((String) jsonUser, User.class); return user; } // Redis 没有再从 mysql 查询 user = userDao.queryUserById(userId); if(null != user){ redisTemplate.opsForValue().set("user:id_" + userId, JsonUtil.object2JsonStr(user)); return user; } return null; }
d. Redis Windows 客户端看到的数据是友好的
因此,推荐使用后一种
代码如下
public User getUserInfoList(Integer age){ //先查redis //User user = (User) redisTemplate.opsForValue().get("user:id_"+age); // 先从 Redis 查询 Object jsonUser = redisTemplate.opsForValue().get("user:id_" + age); User user = null; System.out.println("========================="); System.out.println("========================="); System.out.println("========================="); if(jsonUser != user){ user = JsonUtil.jsonStr2Object((String) jsonUser, User.class); System.out.println("redis"); return user; } System.out.println("mysql"); // Redis 没有再从 mysql 查询 user = approvalMapper.getUserInfoList(age); if (null != user){ redisTemplate.opsForValue().set("user:id_" + age, JsonUtil.object2JsonStr(user)); //redisTemplate.opsForValue().set("user:id_" + age, user); return user; } return null; }
JsonUtil工具类如下
/** * Json 转换工具类 */ public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); /** * 将对象转换成 json 字符串 * @param obj * @return */ public static String object2JsonStr(Object obj){ try { return objectMapper.writeValueAsString(obj); } catch (JsonProcessingException e) { //打印异常信息 e.printStackTrace(); } return null; } /** * 将字符串转换为对象 * @param <T> 泛型 */ public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz){ try { return objectMapper.readValue(jsonStr.getBytes("UTF-8"), clazz); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }