SpringBoot實戰電商項目mall(30k+star)地址:github.com/macrozheng/…java
Spring Data Redis 是Spring 框架提供的用於操做Redis的方式,最近整理了下它的用法,解決了使用過程當中遇到的一些難點與坑點,但願對你們有所幫助。本文涵蓋了Redis的安裝、Spring Cache結合Redis的使用、Redis鏈接池的使用和RedisTemplate的使用等內容。git
這裏提供Linux和Windows兩種安裝方式,因爲Windows下的版本最高只有3.2版本,因此推薦使用Linux下的版本,目前最新穩定版本爲5.0,也是本文中使用的版本。github
這裏咱們使用Docker環境下的安裝方式。redis
docker pull redis:5.0
複製代碼
docker run -p 6379:6379 --name redis \
-v /mydata/redis/data:/data \
-d redis:5.0 redis-server --appendonly yes
複製代碼
想使用Windows版本的朋友可使用如下安裝方式。spring
當Spring Boot 結合Redis來做爲緩存使用時,最簡單的方式就是使用Spring Cache了,使用它咱們無需知道Spring中對Redis的各類操做,僅僅經過它提供的@Cacheable 、@CachePut 、@CacheEvict 、@EnableCaching等註解就能夠實現緩存功能。docker
開啓緩存功能,通常放在啓動類上。數據庫
使用該註解的方法當緩存存在時,會從緩存中獲取數據而不執行方法,當緩存不存在時,會執行方法並把返回結果存入緩存中。通常使用在查詢方法上
,能夠設置以下屬性:apache
使用該註解的方法每次執行時都會把返回結果存入緩存中。通常使用在新增方法上
,能夠設置以下屬性:windows
使用該註解的方法執行時會清空指定的緩存。通常使用在更新或刪除方法上
,能夠設置以下屬性:緩存
<!--redis依賴配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
複製代碼
spring:
redis:
host: 192.168.6.139 # Redis服務器地址
database: 0 # Redis數據庫索引(默認爲0)
port: 6379 # Redis服務器鏈接端口
password: # Redis服務器鏈接密碼(默認爲空)
timeout: 1000ms # 鏈接超時時間
複製代碼
@EnableCaching
@SpringBootApplication
public class MallTinyApplication {
public static void main(String[] args) {
SpringApplication.run(MallTinyApplication.class, args);
}
}
複製代碼
/** * PmsBrandService實現類 * Created by macro on 2019/4/19. */
@Service
public class PmsBrandServiceImpl implements PmsBrandService {
@Autowired
private PmsBrandMapper brandMapper;
@CacheEvict(value = RedisConfig.REDIS_KEY_DATABASE, key = "'pms:brand:'+#id")
@Override
public int update(Long id, PmsBrand brand) {
brand.setId(id);
return brandMapper.updateByPrimaryKeySelective(brand);
}
@CacheEvict(value = RedisConfig.REDIS_KEY_DATABASE, key = "'pms:brand:'+#id")
@Override
public int delete(Long id) {
return brandMapper.deleteByPrimaryKey(id);
}
@Cacheable(value = RedisConfig.REDIS_KEY_DATABASE, key = "'pms:brand:'+#id", unless = "#result==null")
@Override
public PmsBrand getItem(Long id) {
return brandMapper.selectByPrimaryKey(id);
}
}
複製代碼
此時咱們就會想到有沒有什麼辦法讓Redis中存儲的數據變成標準的JSON格式,而後能夠設置必定的過時時間,不設置過時時間容易產生不少沒必要要的緩存數據。
/** * Redis配置類 * Created by macro on 2020/3/2. */
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
/** * redis數據庫自定義key */
public static final String REDIS_KEY_DATABASE="mall";
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisSerializer<Object> serializer = redisSerializer();
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(serializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public RedisSerializer<Object> redisSerializer() {
//建立JSON序列化器
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
return serializer;
}
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//設置Redis緩存有效期爲1天
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
}
複製代碼
SpringBoot 1.5.x版本Redis客戶端默認是Jedis實現的,SpringBoot 2.x版本中默認客戶端是用Lettuce實現的,咱們先來了解下Jedis和Lettuce客戶端。
Jedis在實現上是直連Redis服務,多線程環境下非線程安全,除非使用鏈接池,爲每一個 RedisConnection 實例增長物理鏈接。
Lettuce是一種可伸縮,線程安全,徹底非阻塞的Redis客戶端,多個線程能夠共享一個RedisConnection,它利用Netty NIO框架來高效地管理多個鏈接,從而提供了異步和同步數據訪問方式,用於構建非阻塞的反應性應用程序。
spring:
redis:
lettuce:
pool:
max-active: 8 # 鏈接池最大鏈接數
max-idle: 8 # 鏈接池最大空閒鏈接數
min-idle: 0 # 鏈接池最小空閒鏈接數
max-wait: -1ms # 鏈接池最大阻塞等待時間,負值表示沒有限制
複製代碼
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
複製代碼
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig
at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration$LettucePoolingClientConfigurationBuilder.<init>(LettucePoolingClientConfiguration.java:84) ~[spring-data-redis-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration.builder(LettucePoolingClientConfiguration.java:48) ~[spring-data-redis-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$PoolBuilderFactory.createBuilder(LettuceConnectionConfiguration.java:149) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.createBuilder(LettuceConnectionConfiguration.java:107) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.getLettuceClientConfiguration(LettuceConnectionConfiguration.java:93) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.redisConnectionFactory(LettuceConnectionConfiguration.java:74) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$5caa7e47.CGLIB$redisConnectionFactory$0(<generated>) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$5caa7e47$$FastClassBySpringCGLIB$$b8ae2813.invoke(<generated>) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$5caa7e47.redisConnectionFactory(<generated>) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 111 common frames omitted
複製代碼
Spring Cache 給咱們提供了操做Redis緩存的便捷方法,可是也有不少侷限性。好比說咱們想單獨設置一個緩存值的有效期怎麼辦?咱們並不想緩存方法的返回值,咱們想緩存方法中產生的中間值怎麼辦?此時咱們就須要用到RedisTemplate這個類了,接下來咱們來說下如何經過RedisTemplate來自由操做Redis中的緩存。
定義Redis操做業務類,在Redis中有幾種數據結構,好比普通結構(對象),Hash結構、Set結構、List結構,該接口中定義了大多數經常使用操做方法。
/** * redis操做Service * Created by macro on 2020/3/3. */
public interface RedisService {
/** * 保存屬性 */
void set(String key, Object value, long time);
/** * 保存屬性 */
void set(String key, Object value);
/** * 獲取屬性 */
Object get(String key);
/** * 刪除屬性 */
Boolean del(String key);
/** * 批量刪除屬性 */
Long del(List<String> keys);
/** * 設置過時時間 */
Boolean expire(String key, long time);
/** * 獲取過時時間 */
Long getExpire(String key);
/** * 判斷是否有該屬性 */
Boolean hasKey(String key);
/** * 按delta遞增 */
Long incr(String key, long delta);
/** * 按delta遞減 */
Long decr(String key, long delta);
/** * 獲取Hash結構中的屬性 */
Object hGet(String key, String hashKey);
/** * 向Hash結構中放入一個屬性 */
Boolean hSet(String key, String hashKey, Object value, long time);
/** * 向Hash結構中放入一個屬性 */
void hSet(String key, String hashKey, Object value);
/** * 直接獲取整個Hash結構 */
Map<Object, Object> hGetAll(String key);
/** * 直接設置整個Hash結構 */
Boolean hSetAll(String key, Map<String, Object> map, long time);
/** * 直接設置整個Hash結構 */
void hSetAll(String key, Map<String, Object> map);
/** * 刪除Hash結構中的屬性 */
void hDel(String key, Object... hashKey);
/** * 判斷Hash結構中是否有該屬性 */
Boolean hHasKey(String key, String hashKey);
/** * Hash結構中屬性遞增 */
Long hIncr(String key, String hashKey, Long delta);
/** * Hash結構中屬性遞減 */
Long hDecr(String key, String hashKey, Long delta);
/** * 獲取Set結構 */
Set<Object> sMembers(String key);
/** * 向Set結構中添加屬性 */
Long sAdd(String key, Object... values);
/** * 向Set結構中添加屬性 */
Long sAdd(String key, long time, Object... values);
/** * 是否爲Set中的屬性 */
Boolean sIsMember(String key, Object value);
/** * 獲取Set結構的長度 */
Long sSize(String key);
/** * 刪除Set結構中的屬性 */
Long sRemove(String key, Object... values);
/** * 獲取List結構中的屬性 */
List<Object> lRange(String key, long start, long end);
/** * 獲取List結構的長度 */
Long lSize(String key);
/** * 根據索引獲取List中的屬性 */
Object lIndex(String key, long index);
/** * 向List結構中添加屬性 */
Long lPush(String key, Object value);
/** * 向List結構中添加屬性 */
Long lPush(String key, Object value, long time);
/** * 向List結構中批量添加屬性 */
Long lPushAll(String key, Object... values);
/** * 向List結構中批量添加屬性 */
Long lPushAll(String key, Long time, Object... values);
/** * 從List結構中移除屬性 */
Long lRemove(String key, long count, Object value);
}
複製代碼
RedisService的實現類,使用RedisTemplate來自由操做Redis中的緩存數據。
/** * redis操做實現類 * Created by macro on 2020/3/3. */
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void set(String key, Object value, long time) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
@Override
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
@Override
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
@Override
public Boolean del(String key) {
return redisTemplate.delete(key);
}
@Override
public Long del(List<String> keys) {
return redisTemplate.delete(keys);
}
@Override
public Boolean expire(String key, long time) {
return redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
@Override
public Long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
@Override
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
@Override
public Long incr(String key, long delta) {
return redisTemplate.opsForValue().increment(key, delta);
}
@Override
public Long decr(String key, long delta) {
return redisTemplate.opsForValue().increment(key, -delta);
}
@Override
public Object hGet(String key, String hashKey) {
return redisTemplate.opsForHash().get(key, hashKey);
}
@Override
public Boolean hSet(String key, String hashKey, Object value, long time) {
redisTemplate.opsForHash().put(key, hashKey, value);
return expire(key, time);
}
@Override
public void hSet(String key, String hashKey, Object value) {
redisTemplate.opsForHash().put(key, hashKey, value);
}
@Override
public Map<Object, Object> hGetAll(String key) {
return redisTemplate.opsForHash().entries(key);
}
@Override
public Boolean hSetAll(String key, Map<String, Object> map, long time) {
redisTemplate.opsForHash().putAll(key, map);
return expire(key, time);
}
@Override
public void hSetAll(String key, Map<String, Object> map) {
redisTemplate.opsForHash().putAll(key, map);
}
@Override
public void hDel(String key, Object... hashKey) {
redisTemplate.opsForHash().delete(key, hashKey);
}
@Override
public Boolean hHasKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
}
@Override
public Long hIncr(String key, String hashKey, Long delta) {
return redisTemplate.opsForHash().increment(key, hashKey, delta);
}
@Override
public Long hDecr(String key, String hashKey, Long delta) {
return redisTemplate.opsForHash().increment(key, hashKey, -delta);
}
@Override
public Set<Object> sMembers(String key) {
return redisTemplate.opsForSet().members(key);
}
@Override
public Long sAdd(String key, Object... values) {
return redisTemplate.opsForSet().add(key, values);
}
@Override
public Long sAdd(String key, long time, Object... values) {
Long count = redisTemplate.opsForSet().add(key, values);
expire(key, time);
return count;
}
@Override
public Boolean sIsMember(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
@Override
public Long sSize(String key) {
return redisTemplate.opsForSet().size(key);
}
@Override
public Long sRemove(String key, Object... values) {
return redisTemplate.opsForSet().remove(key, values);
}
@Override
public List<Object> lRange(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
@Override
public Long lSize(String key) {
return redisTemplate.opsForList().size(key);
}
@Override
public Object lIndex(String key, long index) {
return redisTemplate.opsForList().index(key, index);
}
@Override
public Long lPush(String key, Object value) {
return redisTemplate.opsForList().rightPush(key, value);
}
@Override
public Long lPush(String key, Object value, long time) {
Long index = redisTemplate.opsForList().rightPush(key, value);
expire(key, time);
return index;
}
@Override
public Long lPushAll(String key, Object... values) {
return redisTemplate.opsForList().rightPushAll(key, values);
}
@Override
public Long lPushAll(String key, Long time, Object... values) {
Long count = redisTemplate.opsForList().rightPushAll(key, values);
expire(key, time);
return count;
}
@Override
public Long lRemove(String key, long count, Object value) {
return redisTemplate.opsForList().remove(key, count, value);
}
}
複製代碼
測試RedisService中緩存操做的Controller,你們能夠調用測試下。
/** * Redis測試Controller * Created by macro on 2020/3/3. */
@Api(tags = "RedisController", description = "Redis測試")
@Controller
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisService redisService;
@Autowired
private PmsBrandService brandService;
@ApiOperation("測試簡單緩存")
@RequestMapping(value = "/simpleTest", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> simpleTest() {
List<PmsBrand> brandList = brandService.list(1, 5);
PmsBrand brand = brandList.get(0);
String key = "redis:simple:" + brand.getId();
redisService.set(key, brand);
PmsBrand cacheBrand = (PmsBrand) redisService.get(key);
return CommonResult.success(cacheBrand);
}
@ApiOperation("測試Hash結構的緩存")
@RequestMapping(value = "/hashTest", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> hashTest() {
List<PmsBrand> brandList = brandService.list(1, 5);
PmsBrand brand = brandList.get(0);
String key = "redis:hash:" + brand.getId();
Map<String, Object> value = BeanUtil.beanToMap(brand);
redisService.hSetAll(key, value);
Map<Object, Object> cacheValue = redisService.hGetAll(key);
PmsBrand cacheBrand = BeanUtil.mapToBean(cacheValue, PmsBrand.class, true);
return CommonResult.success(cacheBrand);
}
@ApiOperation("測試Set結構的緩存")
@RequestMapping(value = "/setTest", method = RequestMethod.GET)
@ResponseBody
public CommonResult<Set<Object>> setTest() {
List<PmsBrand> brandList = brandService.list(1, 5);
String key = "redis:set:all";
redisService.sAdd(key, (Object[]) ArrayUtil.toArray(brandList, PmsBrand.class));
redisService.sRemove(key, brandList.get(0));
Set<Object> cachedBrandList = redisService.sMembers(key);
return CommonResult.success(cachedBrandList);
}
@ApiOperation("測試List結構的緩存")
@RequestMapping(value = "/listTest", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<Object>> listTest() {
List<PmsBrand> brandList = brandService.list(1, 5);
String key = "redis:list:all";
redisService.lPushAll(key, (Object[]) ArrayUtil.toArray(brandList, PmsBrand.class));
redisService.lRemove(key, 1, brandList.get(0));
List<Object> cachedBrandList = redisService.lRange(key, 0, 3);
return CommonResult.success(cachedBrandList);
}
}
複製代碼
mall項目全套學習教程連載中,關注公衆號第一時間獲取。