添加依賴
<!-- 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; } }
