前言:上一篇文章我們用的是StringredisTemplate,但是它存在一點(diǎn)問題,也迫使我重新寫了代碼,問題是:在我們往緩存中存入數(shù)字形式的String類型時(shí),我們?cè)诶肧pring could將獲取到的數(shù)據(jù)發(fā)送到另一服務(wù)時(shí),我們發(fā)現(xiàn)數(shù)據(jù)已經(jīng)被強(qiáng)轉(zhuǎn)為Integer類型了,因?yàn)槲覀兛赡軅鬏數(shù)臄?shù)據(jù)龐大,類型多樣,為了統(tǒng)一類型,以及開發(fā)方便,所以我將緩存改成RedisTemplate這種類型,進(jìn)行增刪改查的操作,文中沒有特別舉例更新操作,其更新操作與添加操作一樣,當(dāng)key一樣時(shí)進(jìn)行添加就會(huì)覆蓋原value值,完成更新。RedisTemplate需要我們自己去配置它并進(jìn)行實(shí)例化。接下來,舉例子,上代碼:
首先建立Spring boot項(xiàng)目添加Redis依賴
下載導(dǎo)入IDE,我們觀察pom.xml文件:
創(chuàng)新互聯(lián)公司2013年成立,先為蟠龍等服務(wù)建站,蟠龍等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為蟠龍企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
4.0.0
com.test
redis
0.0.1-SNAPSHOT
jar
redis
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.1.0.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
org.springframework.boot
spring-boot-maven-plugin
1.配置application.properties
#redis
spring.redis.host=主機(jī)地址
spring.redis.password=admin
spring.redis.port=6379
spring.redis.timeout=10000
spring.redis.jedis.pool.max-idle=200
spring.redis.jedis.pool.min-idle=300000
spring.redis.jedis.pool.max-active=400
spring.redis.jedis.pool.max-wait=10000
2.我們寫配置配置類實(shí)例化RedisTemplate
package com.test.redis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@Configuration
public class RedisConfig {
/**
* 實(shí)例化 RedisTemplate 對(duì)象
*
* @return
*/
@Bean
public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 設(shè)置數(shù)據(jù)存入 redis 的序列化方式,并開啟事務(wù)
*
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
// 如果不配置Serializer,那么存儲(chǔ)的時(shí)候缺省使用String,如果用User類型存儲(chǔ),那么會(huì)提示錯(cuò)誤User can't cast to
// String!
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 開啟事務(wù)
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
}
3.寫緩存操作的Service層,進(jìn)行增刪改查方法的定義:
package cn.com.dhcc.idatabus.admin.console.service;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Resource
private RedisTemplate template;
/**
* 存儲(chǔ)數(shù)據(jù)或修改數(shù)據(jù)
*
* @param modelMap
* @param mapName
*/
public void setKey(String mapName, Map modelMap) {
HashOperations hps = template.opsForHash();
hps.putAll(mapName, modelMap);
}
/**
* 獲取數(shù)據(jù)Map
*
* @param mapName
* @return
*/
public Map getMapValue(String mapName) {
HashOperations hps = this.template.opsForHash();
return hps.entries(mapName);
}
/**
* 獲取數(shù)據(jù)value
*
* @param mapName
* @param hashKey
* @return
*/
public Object getValue(String mapName, String hashKey) {
HashOperations hps = this.template.opsForHash();
return hps.get(mapName, hashKey);
}
/**
* 批量刪除緩存數(shù)據(jù)
*
* @param keys
*/
public void deleteData(List keys) {
// 執(zhí)行批量刪除操作時(shí)先序列化template
template.setKeySerializer(new JdkSerializationRedisSerializer());
template.delete(keys);
}
}
4.本次例子的實(shí)體類
package com.test.redis.entity;
public class User {
private Integer id;
private String name;
private String password;
public User() {
super();
}
public User(Integer id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
}
}
5.編寫Controller層,來實(shí)現(xiàn)緩存的操作
package com.test.redis.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.test.redis.entity.User;
import com.test.redis.service.RedisService;
@Controller
public class UserController {
private static final String mapName="mapName";
@Autowired
private RedisService redisService;
@GetMapping( "/templateAdd.do")
@ResponseBody
public Map addUser(HttpServletRequest request){
Map modelMap=new HashMap();
User user=new User();
user.setName("hehename");
user.setPassword("hehePassword");
//存放hash值
modelMap.put("name", user.getName());
modelMap.put("password", user.getPassword());
redisService.setKey(mapName, modelMap);
//獲取map集合
Map modelMap1= redisService.getMapValue(mapName);
Object value= redisService.getValue(mapName, "name");
System.out.println(" value : "+value);
modelMap1.put("從緩存中根據(jù)key取到的value", value);
return modelMap1;
}
@GetMapping( "/templateDelete.do")
@ResponseBody
public Map deleteUser(HttpServletRequest request){
//獲取即將刪除的key值,這里我們做的批量刪除
List keys=new ArrayList<>();
keys.add("heheanme");
//開始執(zhí)行刪除操作
redisService.deleteData(keys);
//獲取map集合
Map modelMap1= redisService.getMapValue(mapName);
Object value= redisService.getValue(mapName, "name");
System.out.println(" value : "+value);
modelMap1.put("從緩存中根據(jù)key取到的value", value);
return modelMap1;
}
}
接下來,我們?cè)L問Controller路徑
(1)http://localhost:8081/templateAdd.do
結(jié)果:
(2)http://localhost:8081/templateDelete.do
結(jié)果: