說明
一個系統(tǒng)在于數(shù)據(jù)庫交互的過程中骡和,內(nèi)存的速度遠遠快于硬盤速度,當(dāng)我們重復(fù)地獲取相同數(shù)據(jù)時此蜈,我們一次又一次地請求數(shù)據(jù)庫或遠程服務(wù)即横,者無疑時性能上地浪費,這會導(dǎo)致大量時間被浪費在數(shù)據(jù)庫查詢或者遠程方法調(diào)用上致使程序性能惡化裆赵,于是有了“緩存”东囚。
完整代碼地址在結(jié)尾!战授!
第一步页藻,在pom.xml加入依賴,如下
<!-- RedisTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Jackson 工具 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
第二步植兰,在application.yml配置文件配置redis
spring:
redis:
database: 0 # redis 數(shù)據(jù)庫索引(默認為0)
host: xxx # ip地址
password: xxx # redis 服務(wù)器連接密碼(默認為空)
port: 6379
timeout: 12000 # 連接超時時間(毫秒)份帐,默認2000ms
# cluster:
# nodes: xxx:7000,xxx:7001,xxx:7002
# maxRedirects: 6
jedis:
pool:
max-active: 8 # 連接池最大連接數(shù)(使用負值表示沒有限制)
max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-idle: 8 # 連接池中的最大空閑連接
min-idle: 0 # 連接池中的最小空閑連接
cache:
redis:
# 過期時間(毫秒)。默認情況下楣导,永不過期废境。
time-to-live: 1d
# 寫入redis時是否使用鍵前綴。
use-key-prefix: true
application:
name: redis-demo-server
server:
port: 8095
第三步,由于RedisTemplate 默認的序列化方式為 JdkSerializeable噩凹,StringRedisTemplate的默認序列化方式為StringRedisSerializer巴元,使用客戶端查看的時候會亂碼,修改序列化方式解決該問題驮宴,創(chuàng)建RedisConfig配置類
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @Description: redistemplate 配置
* @Author: luoyu
* @Date: 2020/1/15 11:20
* @Version: 1.0.0
*/
@Configuration
@EnableCaching
public class RedisConfig {
/**
* @author luoyu
* @description redisTemplate 序列化使用的jdkSerializeable, 存儲二進制字節(jié)碼, 所以自定義序列化類
* @param redisConnectionFactory
* @return RedisTemplate<Object, Object>
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替換默認序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化輸入的類型逮刨,類必須是非final修飾的,final修飾的類堵泽,比如String,Integer等會跑出異常修己,保留這行會報錯:Unexpected token (VALUE_STRING)
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 設(shè)置value的序列化規(guī)則和 key的序列化規(guī)則
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
@Bean
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
/**
* 二者選其一即可
*/
// @Bean
// public RedisCacheConfiguration redisCacheConfiguration() {
// Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化輸入的類型,類必須是非final修飾的迎罗,final修飾的類睬愤,比如String,Integer等會跑出異常,保留這行會報錯:Unexpected token (VALUE_STRING)
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// serializer.setObjectMapper(objectMapper);
// return RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
// }
}
第四步佳谦,直接用RedisTemplate操作redis比較麻煩戴涝,因此直接封裝好一個RedisUtils工具類(本人在網(wǎng)上找到的比較完善的),這樣寫代碼更方便點钻蔑。這個RedisUtils交給spring容器管理啥刻,使用時直接注入使用即可
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/*
* @Description: Redis工具類,基于spring和redis的redisTemplate工具類咪笑。針對所有的hash可帽,都是以h開頭的方法。
* 針對所有的Set窗怒,都是以s開頭的方法映跟。不含通用方法。針對所有的List扬虚,都是以l開頭的方法
* @Author: luoyu
* @Date: 2020/1/15 11:20
* @Version: 1.0.0
*/
@Component
@Slf4j
public class RedisUtils {
@Resource
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================
/**
* 指定緩存失效時間
* @param key 鍵
* @param time 時間(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 根據(jù)key 獲取過期時間
* @param key 鍵 不能為null
* @return 時間(秒) 返回0代表為永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判斷key是否存在
* @param key 鍵
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 刪除緩存
* @param key 可以傳一個值 或多個
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通緩存獲取
* @param key 鍵
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通緩存放入
* @param key 鍵
* @param value 值
* @return true成功 false失敗
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 普通緩存放入并設(shè)置時間
* @param key 鍵
* @param value 值
* @param time 時間(秒) time要大于0 如果time小于等于0 將設(shè)置無限期
* @return true成功 false 失敗
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 遞增 適用場景: https://blog.csdn.net/y_y_y_k_k_k_k/article/details/79218254 高并發(fā)生成訂單號努隙,秒殺類的業(yè)務(wù)邏輯等。辜昵。
* @param key 鍵
* @param delta 要增加幾(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("遞增因子必須大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 遞減
* @param key 鍵
* @param delta 要減少幾(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("遞減因子必須大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
* @param key 鍵 不能為null
* @param item 項 不能為null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 獲取hashKey對應(yīng)的所有鍵值
* @param key 鍵
* @return 對應(yīng)的多個鍵值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 鍵
* @param map 對應(yīng)多個鍵值
* @return true 成功 false 失敗
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* HashSet 并設(shè)置時間
* @param key 鍵
* @param map 對應(yīng)多個鍵值
* @param time 時間(秒)
* @return true成功 false失敗
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
* @param key 鍵
* @param item 項
* @param value 值
* @return true 成功 false失敗
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
* @param key 鍵
* @param item 項
* @param value 值
* @param time 時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間
* @return true 成功 false失敗
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 刪除hash表中的值
* @param key 鍵 不能為null
* @param item 項 可以使多個 不能為null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判斷hash表中是否有該項的值
* @param key 鍵 不能為null
* @param item 項 不能為null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash遞增 如果不存在,就會創(chuàng)建一個 并把新增后的值返回
* @param key 鍵
* @param item 項
* @param by 要增加幾(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash遞減
* @param key 鍵
* @param item 項
* @param by 要減少記(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根據(jù)key獲取Set中的所有值
* @param key 鍵
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
log.error(key, e);
return null;
}
}
/**
* 根據(jù)value從一個set中查詢,是否存在
* @param key 鍵
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 將數(shù)據(jù)放入set緩存
* @param key 鍵
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
/**
* 將set數(shù)據(jù)放入緩存
* @param key 鍵
* @param time 時間(秒)
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
/**
* 獲取set緩存的長度
* @param key 鍵
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
/**
* 移除值為value的
* @param key 鍵
* @param values 值 可以是多個
* @return 移除的個數(shù)
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
// ============================zset=============================
/**
* 根據(jù)key獲取Set中的所有值
* @param key 鍵
* @return
*/
public Set<Object> zSGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
log.error(key, e);
return null;
}
}
/**
* 根據(jù)value從一個set中查詢,是否存在
* @param key 鍵
* @param value 值
* @return true 存在 false不存在
*/
public boolean zSHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
log.error(key, e);
return false;
}
}
public Boolean zSSet(String key, Object value, double score) {
try {
return redisTemplate.opsForZSet().add(key, value, 2);
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 將set數(shù)據(jù)放入緩存
* @param key 鍵
* @param time 時間(秒)
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long zSSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
/**
* 獲取set緩存的長度
* @param key 鍵
* @return
*/
public long zSGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
/**
* 移除值為value的
* @param key 鍵
* @param values 值 可以是多個
* @return 移除的個數(shù)
*/
public long zSetRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
// ===============================list=================================
/**
* 獲取list緩存的內(nèi)容
* 取出來的元素 總數(shù) end-start+1
* @param key 鍵
* @param start 開始 0 是第一個元素
* @param end 結(jié)束 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
log.error(key, e);
return null;
}
}
/**
* 獲取list緩存的長度
* @param key 鍵
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
/**
* 通過索引 獲取list中的值
* @param key 鍵
* @param index 索引 index>=0時荸镊, 0 表頭,1 第二個元素堪置,依次類推躬存;index<0時,-1舀锨,表尾岭洲,-2倒數(shù)第二個元素,依次類推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
log.error(key, e);
return null;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 將list放入緩存
* @param key 鍵
* @param value 值
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 根據(jù)索引修改list中的某條數(shù)據(jù)
* @param key 鍵
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
/**
* 移除N個值為value
* @param key 鍵
* @param count 移除多少個
* @param value 值
* @return 移除的個數(shù)
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
log.error(key, e);
return 0;
}
}
}
第五步坎匿,編寫單元測試類盾剩,RedisApplicationTests雷激,并進行測試,只列舉了部分方法彪腔,至此springboot整合redis完成控轿。
import com.luoyu.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
@Slf4j
// 獲取啟動類穗熬,加載配置,確定裝載 Spring 程序的裝載方法圈匆,它回去尋找 主配置啟動類(被 @SpringBootApplication 注解的)
@SpringBootTest
class RedisApplicationTests {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private RedisUtil redisUtil;
@Test
void redisTemplateSetStringTest() {
redisTemplate.opsForValue().set("a","c");
}
@Test
void redisTemplateGetStringTest() {
log.info(redisTemplate.opsForValue().get("a").toString());
}
@Test
void redisUtilDeteleStringTest() {
redisTemplate.delete("a");
}
@Test
void redisUtilGetStringTest() {
log.info(redisUtil.get("a").toString());
}
@BeforeEach
void testBefore(){
log.info("測試開始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
@AfterEach
void testAfter(){
log.info("測試結(jié)束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
第六步快毛,開始整合SpringCache緩存功能格嗅,編寫服務(wù)類,Test唠帝,TestService屯掖,TestServiceImpl,如下
Test
import lombok.Data;
import java.io.Serializable;
@Data
public class Test implements Serializable {
private String id;
private String name;
private int age;
private String sex;
}
TestService
import com.luoyu.redis.entity.Test;
public interface TestService {
Test get(String id);
boolean add(Test test);
boolean delete(String id);
boolean update(Test test);
}
TestServiceImpl
import com.luoyu.redis.entity.Test;
import com.luoyu.redis.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class TestServiceImpl implements TestService {
@Override
public Test get(String id) {
log.info("沒有使用緩存襟衰,創(chuàng)建一個新對象返回贴铜,并設(shè)置到緩存");
Test test = new Test();
test.setId(id);
test.setName("測試name");
test.setAge(12);
test.setSex("男");
return test;
}
@Override
public boolean add(Test test) {
log.info("創(chuàng)建id為:" + test.getId() + "的對象存起來,并設(shè)置到緩存瀑晒,對象為:" + test.toString());
return true;
}
@Override
public boolean delete(String id) {
log.info("刪除id為:" + id + "的對象绍坝,并從緩存中刪除");
return true;
}
@Override
public boolean update(Test test) {
log.info("更新id為:" + test.getId() + "的對象,并更新到緩存苔悦,新對象為:" + test.toString());
return true;
}
}
第七步轩褐,編寫TestController類,如下
import com.luoyu.redis.entity.Test;
import com.luoyu.redis.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
/**
* 查詢一個對象并返回
*
* @return
*/
@GetMapping("/get")
@Cacheable(value = "redis.test.key:", key = "#id")
public Test get(@RequestParam(required = true) String id) {
log.info("查詢一個對象并返回");
return testService.get(id);
}
/**
* 刪除一個對象
*
* @return
*/
@DeleteMapping("/delete")
@CacheEvict(value = "redis.test.key:", key = "#id")
public boolean delete(@RequestParam(required = true) String id) {
log.info("刪除一個對象");
return testService.delete(id);
}
/**
* 新增一個對象
*
* @return
*/
@PostMapping("/add")
@Cacheable(value = "redis.test.key:", key = "#test.getId()")
public Test add(@RequestBody Test test) {
log.info("新增一個對象玖详,結(jié)果:" + testService.add(test));
return test;
}
/**
* 更新一個對象
*
* @return
*/
@PutMapping("/update")
@CachePut(value = "redis.test.key:", key = "#test.getId()")
public Test update(@RequestBody Test test) {
log.info("更新一個對象把介,結(jié)果:" + testService.update(test));
return test;
}
}
第八步,使用postman工具調(diào)api接口
- 通過查看控制臺日志打印情況蟋座,可得出整合SpringCache緩存功能成功拗踢,本文只做簡單的操作方式,如需復(fù)雜使用方式向臀,請自行百度查詢
第九步巢墅,各種注解使用方式說明,如下
注解說明
- @Cacheable:觸發(fā)緩存寫入飒硅。
- @CacheEvict:觸發(fā)緩存清除砂缩。
- @CachePut:更新緩存(不會影響到方法的運行)。
- @Caching:重新組合要應(yīng)用于方法的多個緩存操作三娩。
- @CacheConfig:設(shè)置類級別上共享的一些常見緩存設(shè)置庵芭。
@Cacheable/@CachePut/@CacheEvict等注解的主要參數(shù)
名稱 | 解釋 | 示例 |
---|---|---|
value | 緩存的名稱,在 spring 配置文件中定義雀监,必須指定至少一個 | @Cacheable(value=”mycache”) 或者@Cacheable(value={”cache1”,”cache2”}) |
key | 緩存的 key双吆,可以為空眨唬,如果指定要按照 SpEL 表達式編寫,如果不指定好乐,則缺省按照方法的所有參數(shù)進行組合 | @Cacheable(value=”testcache”,key=”#id”) |
condition | 緩存的條件匾竿,可以為空,使用 SpEL 編寫蔚万,返回 true 或者 false岭妖,只有為 true 才進行緩存/清除緩存 | @Cacheable(value=”testcache”,condition=”#userName.length()>2”) |
unless | 否定緩存。當(dāng)條件結(jié)果為TRUE時反璃,就不會緩存 | @Cacheable(value=”testcache”,unless=”#userName.length()>2”) |
allEntries(@CacheEvict ) | 是否清空所有緩存內(nèi)容昵慌,缺省為 false,如果指定為 true淮蜈,則方法調(diào)用后將立即清空所有緩存 | @CachEvict(value=”testcache”,allEntries=true) |
beforeInvocation(@CacheEvict) | 是否在方法執(zhí)行前就清空斋攀,缺省為 false,如果指定為 true梧田,則在方法還沒有執(zhí)行的時候就清空緩存淳蔼,缺省情況下,如果方法執(zhí)行拋出異常裁眯,則不會清空緩存 | @CachEvict(value=”testcache”鹉梨,beforeInvocation=true) |
SpEL上下文數(shù)據(jù)說明
名稱 | 位置 | 描述 | 示例 |
---|---|---|---|
methodName | root對象 | 當(dāng)前被調(diào)用的方法名 | #root.methodname |
method | root對象 | 當(dāng)前被調(diào)用的方法 | #root.method.name |
target | root對象 | 當(dāng)前被調(diào)用的目標(biāo)對象實例 | #root.target |
targetClass | root對象 | 當(dāng)前被調(diào)用的目標(biāo)對象的類 | #root.targetClass |
args | root對象 | 當(dāng)前被調(diào)用的方法的參數(shù)列表 | #root.args[0] |
caches | root對象 | 當(dāng)前方法調(diào)用使用的緩存列表 | #root.caches[0].name |
Argument Name | 執(zhí)行上下文 | 當(dāng)前被調(diào)用的方法的參數(shù),如findArtisan(Artisan artisan),可以通過#artsian.id獲得參數(shù) | #artsian.id |
result | 執(zhí)行上下文 | 方法執(zhí)行后的返回值(僅當(dāng)方法執(zhí)行后的判斷有效未状,如 unless cacheEvict的beforeInvocation=false) | #result |
注意:
- 當(dāng)我們要使用root對象的屬性作為key時我們也可以將“#root”省略俯画,因為Spring默認使用的就是root對象的屬性。 如@Cacheable(key = "targetClass + methodName +#p0")
- 使用方法參數(shù)時我們可以直接使用“#參數(shù)名”或者“#p參數(shù)index”司草。 如:@Cacheable(value="users", key="#id")艰垂,@Cacheable(value="users", key="#p0")
SpEL提供了多種運算符
類型 | 運算符 |
---|---|
關(guān)系 | <,>埋虹,<=猜憎,>=,==搔课,!=胰柑,lt,gt爬泥,le柬讨,ge,eq袍啡,ne |
算術(shù) | +踩官,- ,* 境输,/蔗牡,%颖系,^ |
邏輯 | &&,||辩越,!嘁扼,and,or黔攒,not趁啸,between,instanceof |
條件 | ?: (ternary)亏钩,?: (elvis) |
正則表達式 | matches |
其他類型 | ?.莲绰,?[…],![…]姑丑,$[…] |
第十步,開始使用Pipelined管道進行批量操作
Redis是采用基于C/S模式的請求/響應(yīng)協(xié)議的TCP服務(wù)器辞友。
性能問題1:redis客戶端發(fā)送多條請求栅哀,后面的請求需要等待前面的請求處理完后,才能進行處理称龙,而且每個請求都存在往返時間RRT(Round Trip Time)留拾,即使redis性能極高,當(dāng)數(shù)據(jù)量足夠大鲫尊,也會極大影響性能痴柔,還可能會引起其他意外情況。
性能問題2:上面的性能問題1我們可以通過scan命令來解決疫向,如何來設(shè)置count又是一個問題咳蔚,設(shè)置不好,同樣會有大量請求存在搔驼,即使設(shè)置到1w(推薦最大值)谈火,如果掃描的數(shù)據(jù)量太大,這個問題同樣不能避免舌涨。每個請求都會經(jīng)歷三次握手糯耍、四次揮手,在處理大量連接時囊嘉,處理完后温技,揮手會產(chǎn)生大量time-wait,如果該服務(wù)器提供其他服務(wù)扭粱,可能對其他服務(wù)造成影響舵鳞。
然而,使用Pipeline可以解決以上問題焊刹。具體使用方法如下系任。
新增工具類JsonUtils恳蹲,MapUtils,如下
JsonUtils
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* JsonUtils
*
* @author luoyu
* @date 2018/10/08 19:13
* @description Json工具類俩滥,依賴jackson
*/
@Slf4j
public class JsonUtils {
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
/**
* object轉(zhuǎn)換成json
*/
public static <T>String objectToJson(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.error("object轉(zhuǎn)換成json失敿卫佟:", e);
return null;
}
}
/**
* json轉(zhuǎn)換成object
*/
public static <T>T jsonToObject(String src, Class<T> clazz){
if(StringUtils.isEmpty(src) || clazz == null){
return null;
}
try {
return clazz.equals(String.class) ? (T) src : objectMapper.readValue(src, clazz);
} catch (Exception e) {
log.error("json轉(zhuǎn)換成object失敗:", e);
return null;
}
}
/**
* json轉(zhuǎn)換成map
*/
public static <T>Map<String, Object> jsonToMap(String src) {
if(StringUtils.isEmpty(src)){
return null;
}
try {
return objectMapper.readValue(src, Map.class);
} catch (Exception e) {
log.error("json轉(zhuǎn)換成map失斔伞:", e);
return null;
}
}
/**
* json轉(zhuǎn)換成list
*/
public static <T>List<T> jsonToList(String jsonArrayStr, Class<T> clazz) {
try{
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
return objectMapper.readValue(jsonArrayStr, javaType);
}catch (Exception e) {
log.error("json轉(zhuǎn)換成list失敶沓馈:", e);
return null;
}
}
}
MapUtils
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
* MapUtils
*
* @author luoyu
* @date 2018/10/22 19:38
* @description Map工具類
*/
@Slf4j
public class MapUtils extends HashMap<String, Object> {
@Override
public MapUtils put(String key, Object value) {
super.put(key,value);
return this;
}
/**
* object轉(zhuǎn)換成map
*/
public static <T>Map<String, Object> objectToMap(T obj) {
if (obj == null) {
return null;
}
try {
Field[] fields = obj.getClass().getDeclaredFields();
Map<String, Object> map = new HashMap<>();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
} catch (Exception e) {
log.error("object轉(zhuǎn)換成map失敗:", e);
return null;
}
}
/**
* map轉(zhuǎn)換成object
*/
public static <T>T mapToObject(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
try {
T obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
} catch (Exception e) {
log.error("map轉(zhuǎn)換成object失敼揖荨:", e);
return null;
}
}
}
第十一步以清,修改TestService,TestServiceImpl添加方法崎逃,如下
TestService
import com.luoyu.redis.entity.Test;
import java.util.List;
public interface TestService {
Test get(String id);
boolean add(Test test);
boolean delete(String id);
boolean update(Test test);
List<Test> gets();
void sets(List<Test> tests);
void deletes();
}
TestServiceImpl
import com.luoyu.redis.entity.Test;
import com.luoyu.redis.service.TestService;
import com.luoyu.redis.util.JsonUtils;
import com.luoyu.redis.util.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
@Slf4j
@Service
public class TestServiceImpl implements TestService {
@Autowired
private RedisTemplate redisTemplate;
private static final String PIPELINED_KEY = "pipelined:";
@Override
public Test get(String id) {
log.info("沒有使用緩存掷倔,創(chuàng)建一個新對象返回,并設(shè)置到緩存");
Test test = new Test();
test.setId(id);
test.setName("測試name");
test.setAge(12);
test.setSex("男");
return test;
}
@Override
public boolean add(Test test) {
log.info("創(chuàng)建id為:" + test.getId() + "的對象存起來个绍,并設(shè)置到緩存勒葱,對象為:" + test.toString());
return true;
}
@Override
public boolean delete(String id) {
log.info("刪除id為:" + id + "的對象,并從緩存中刪除");
return true;
}
@Override
public boolean update(Test test) {
log.info("更新id為:" + test.getId() + "的對象巴柿,并更新到緩存凛虽,新對象為:" + test.toString());
return true;
}
@Override
public List<Test> gets() {
// 獲取指定key的所有hashKey
Set<String> testSet = redisTemplate.keys(PIPELINED_KEY + "*");
if (CollectionUtils.isEmpty(testSet)) {
return Collections.emptyList();
}
// 根據(jù)hashKey依次獲取所有value
List<Map> mapList = redisTemplate.executePipelined((RedisCallback<Map>) connection -> {
if (!CollectionUtils.isEmpty(testSet)) {
for (String item : testSet) {
connection.get((item).getBytes());
}
}
return null;
});
List<Test> testList = new ArrayList<>();
mapList.forEach(mapListItem -> {
Test test = MapUtils.mapToObject(mapListItem, Test.class);
testList.add(test);
});
return testList;
}
@Override
public void sets(List<Test> tests) {
redisTemplate.executePipelined((RedisCallback) connection -> {
if (!CollectionUtils.isEmpty(tests)) {
for (Test item : tests) {
connection.set((PIPELINED_KEY + item.getId()).getBytes(), JsonUtils.objectToJson(item).getBytes(), Expiration.seconds(1000), RedisStringCommands.SetOption.UPSERT);
}
}
return null;
});
}
@Override
public void deletes() {
// 獲取指定key的所有hashKey
Set<String> testSet = redisTemplate.keys(PIPELINED_KEY + "*");
if (CollectionUtils.isEmpty(testSet)) {
return;
}
redisTemplate.executePipelined((RedisCallback) connection -> {
if (!CollectionUtils.isEmpty(testSet)) {
for (String item : testSet) {
connection.del((item).getBytes());
}
}
return null;
});
}
}
第十二步,修改單元測試類广恢,RedisApplicationTests凯旋,添加新測試方法并進行測試,如下
import com.luoyu.redis.service.TestService;
import com.luoyu.redis.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Slf4j
// 獲取啟動類钉迷,加載配置至非,確定裝載 Spring 程序的裝載方法,它回去尋找 主配置啟動類(被 @SpringBootApplication 注解的)
@SpringBootTest
class RedisApplicationTests {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private TestService testService;
@Autowired
private RedisUtils redisUtils;
@Test
void redisTemplateSetStringTest() {
redisTemplate.opsForValue().set("a","c");
}
@Test
void redisTemplateGetStringTest() {
log.info(redisTemplate.opsForValue().get("a").toString());
}
@Test
void redisUtilDeteleStringTest() {
redisTemplate.delete("a");
}
@Test
void redisUtilGetStringTest() {
log.info(redisUtils.get("a").toString());
}
@Test
void redisTemplatePipelinedGetTest() {
testService.gets().forEach(x -> log.info(x.toString()));
}
@Test
void redisTemplatePipelinedSetTest() {
List<com.luoyu.redis.entity.Test> testList = new ArrayList<>();
for (int i = 0; i < 500; i++) {
com.luoyu.redis.entity.Test test = new com.luoyu.redis.entity.Test();
test.setId(i + "");
test.setAge(i * i);
test.setName("name" + i);
test.setSex("sex" + i);
testList.add(test);
}
testService.sets(testList);
}
@Test
void redisTemplatePipelinedDeleteTest() {
testService.deletes();
}
@BeforeEach
void testBefore(){
log.info("測試開始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
@AfterEach
void testAfter(){
log.info("測試結(jié)束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}