SpringBoot怎么整合Redis实现热点数据缓存

我们以IDEA + SpringBoot作为 Java中整合Redis的使用 的测试环境

首先,我们需要导入Redis的maven依赖

<
!-- Redis的maven依赖包 -->

<
dependency>

<
groupId>
org.springframework.boot<
/groupId>

<
artifactId>
spring-boot-starter-data-redis<
/artifactId>

<
/dependency>

其次,我们需要在配置文件中配置你的Redis配置信息,我使用的是 .yml文件格式

# redis配置
spring:
redis:
# r服务器地址
host: 127.0.0.1
# 服务器端口
port: 6379
# 数据库索引(默认0)
database: 0
# 连接超时时间(毫秒)
timeout: 10s
jedis:
pool:
# 连接池中的最大空闲连接数
max-idle: 8
# 连接池中的最小空闲连接数
min-idle: 0
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1

SpringBoot+Redis:从入门到热点数据缓存化

对 redis 做自定义配置

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

import com.fasterxml.jackson.annotation.PropertyAccessor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfigurer extends CachingConfigurerSupport {

/**
* redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
*/
@Bean
public RedisTemplate<
String, Object>
redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
// 配置redisTemplate
RedisTemplate<
String, Object>
redisTemplate = new RedisTemplate<
>
();

redisTemplate.setConnectionFactory(lettuceConnectionFactory);

// 设置序列化
Jackson2JsonRedisSerializer<
Object>
redisSerializer = getRedisSerializer();

// key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());

// value序列化
redisTemplate.setValueSerializer(redisSerializer);

// Hash key序列化
redisTemplate.setHashKeySerializer(new StringRedisSerializer());

// Hash value序列化
redisTemplate.setHashValueSerializer(redisSerializer);

redisTemplate.afterPropertiesSet();

return redisTemplate;

}

/**
* 设置Jackson序列化
*/
private Jackson2JsonRedisSerializer<
Object>
getRedisSerializer() {
Jackson2JsonRedisSerializer<
Object>
redisSerializer = new Jackson2JsonRedisSerializer<
>
(Object.class);

ObjectMapper om = new ObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

redisSerializer.setObjectMapper(om);

return redisSerializer;

}
}

然后,我们需要创建一个RedisUtil来对Redis数据库进行操作

package com.zyxx.test.utils;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Component;


/**
* @ClassName RedisUtil
* @Author
* @Date 2019-08-03 17:29:29
* @Version 1.0
**/
@Component
public class RedisUtil {

@Autowired
private RedisTemplate<
String, String>
template;


/**
* 读取数据
*
* @param key
* @return
*/
public String get(final String key) {
return template.opsForValue().get(key);

}

/**
* 写入数据
*/
public boolean set(final String key, String value) {
boolean res = false;

try {
template.opsForValue().set(key, value);

res = true;

} catch (Exception e) {
e.printStackTrace();

}
return res;

}

/**
* 根据key更新数据
*/
public boolean update(final String key, String value) {
boolean res = false;

try {
template.opsForValue().getAndSet(key, value);

res = true;

} catch (Exception e) {
e.printStackTrace();

}
return res;

}

/**
* 根据key删除数据
*/
public boolean del(final String key) {
boolean res = false;

try {
template.delete(key);

res = true;

} catch (Exception e) {
e.printStackTrace();

}
return res;

}

/**
* 是否存在key
*/
public boolean hasKey(final String key) {
boolean res = false;

try {
res = template.hasKey(key);

} catch (Exception e) {
e.printStackTrace();

}
return res;

}

/**
* 给指定的key设置存活时间
* 默认为-1,表示永久不失效
*/
public boolean setExpire(final String key, long seconds) {
boolean res = false;

try {
if (0 <
seconds) {
res = template.expire(key, seconds, TimeUnit.SECONDS);

}
} catch (Exception e) {
e.printStackTrace();

}
return res;

}

/**
* 获取指定key的剩余存活时间
* 默认为-1,表示永久不失效,-2表示该key不存在
*/
public long getExpire(final String key) {
long res = 0;

try {
res = template.getExpire(key, TimeUnit.SECONDS);

} catch (Exception e) {
e.printStackTrace();

}
return res;

}

/**
* 移除指定key的有效时间
* 当key的有效时间为-1即永久不失效和当key不存在时返回false,否则返回true
*/
public boolean persist(final String key) {
boolean res = false;

try {
res = template.persist(key);

} catch (Exception e) {
e.printStackTrace();

}
return res;

}

}

最后,我们可以使用单元测试来检测我们在RedisUtil中写的操作Redis数据库的方法

package com.zyxx.test;


import com.zyxx.test.utils.RedisUtil;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;


@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTest {

@Resource
private RedisUtil redisUtil;


@Test
public void setRedis() {
boolean res = redisUtil.set("
jay"
, "
周杰伦 - 《以父之名》"
);

System.out.println(res);

}

@Test
public void getRedis() {
String res = redisUtil.get("
jay"
);

System.out.println(res);

}


@Test
public void updateRedis() {
boolean res = redisUtil.update("
jay"
, "
周杰伦 - 《夜的第七章》"
);

System.out.println(res);

}

@Test
public void delRedis() {
boolean res = redisUtil.del("
jay"
);

System.out.println(res);

}

@Test
public void hasKey() {
boolean res = redisUtil.hasKey("
jay"
);

System.out.println(res);

}

@Test
public void expire() {
boolean res = redisUtil.setExpire("
jay"
, 100);

System.out.println(res);

}

@Test
public void getExpire() {
long res = redisUtil.getExpire("
jay"
);

System.out.println(res);

}

@Test
public void persist() {
boolean res = redisUtil.persist("
jay"
);

System.out.println(res);

}

}
  • 建议使用redis-desktop-manager作为Redis数据库中数据的显示工具

  • 至此,我们在日常项目中整合Redis的基本使用操作就完成了,但在实际项目中,可能会涉及到更复杂的用法,可以根据你的业务需求调整Redis的使用即可。



随着互联网技术的不断升级,数据处理和缓存技术也在不断地进步和完善。而SpringBoot作为一款流行的Java后端框架,其与Redis的整合也变得越来越流行。本文将带您从入门到实现热点数据缓存化的过程。
一、Redis介绍与安装
Redis是一种基于内存的键值对存储数据库,它提供了多种高级数据结构,支持多种字符编码,常用于缓存、消息发布订阅、排行榜、实时系统等。要使用Redis,我们需要先安装和配置Redis的环境,具体过程可参考《Redis安装指南》。
二、Redis的Java客户端Jedis
Jedis是Redis的Java客户端之一,它提供了高效的、线程安全的、可靠的Redis操作。通过使用Jedis,我们可以方便地进行Redis的连接、数据读写、缓存操作等。我们需要在SpringBoot工程中加入Jedis的依赖,然后进行配置。
三、SpringBoot整合Redis
SpringBoot整合Redis,需要在pom.xml文件中添加redis的starter依赖。在application.yaml文件中进行配置,配置服务器名称、端口号等信息,并注入RedisTemplate和RedisConnectionFactory等Bean实例。
四、Redis缓存注解
在Spring Data Redis中,提供了对数据的缓存支持,通过使用@Cacheable、@CachePut、@CacheEvict等注解,可以方便地对方法的返回值进行缓存、更新缓存和清除缓存等操作。我们可以为我们的Service层的方法,使用相应的缓存注解来实现缓存功能。
五、实现热点数据缓存
热点数据指的是经常被访问的数据,我们可以通过将热点数据缓存起来,来提高系统的性能和响应速度。通过使用SpringBoot与Redis的整合,并结合缓存注解的使用,可以方便地对热点数据进行缓存。我们可以通过设置缓存的过期时间,避免数据过期不更新的问题。
六、Redis分布式锁
Redis还提供了分布式锁的功能,可以保证在多个应用或多线程环境中,对同一资源的访问是互斥的。可以使用RedisTemplate或Jedis实现分布式锁,具体细节可以参考《Redis分布式锁实现》。
七、Redis集群
随着业务需求的不断增长,单实例的Redis可能会出现性能瓶颈或单点故障问题。此时,我们可以采用Redis集群的方式来提高查询速度和提高可用性。Redis集群的部署方式有多种,可以参考《Redis集群指南》来实现高可用的Redis集群。
通过阅读本文,您可以学习到SpringBoot与Redis的整合方式、缓存注解的使用、实现热点数据缓存、分布式锁和Redis集群等内容。Redis作为一种流行的高速缓存和消息队列技术,其在互联网技术领域中的应用越来越广泛,相信能够帮助开发人员更好地提高系统的性能和响应速度,减少响应时间。