话不多说直接开始:
如果没有安装 redis 或者 没有在服务器安装 redis 的,建议看一下这个课程,很详细
https://www.bilibili.com/video/BV1S54y1R7SB?p=11&spm_id_from=pageDriver
不会用基本 API 的:
redis 常用命令
redis 中 string 类型常用 API
redis:list 和 set 和 zset 类型的简单学习
都差不都了以后,(使用 RedisDesktopManager 或其他能够连接远程 redis 后),开始整合 SpringBoot
首先,引入 maven依赖:
org.springframework.boot
spring-boot-starter-data-redis
yml 文件:
这里有 mysql 和 redis 的,需要写上host,端口,密码和默认数据库
spring:
redis:
host: 8.140.xx.xxx
port: 6379
database: 0
password: xxxx
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://8.xxxxx55/qingxxxxxxxxmuity?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: roxxxxx
password: Txxxxxx
开始编写redis的配置类:
@Component
@EnableCaching
@EnableAutoConfiguration
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
private static final long DEFAULT_TTL = 999999L;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int database;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setDatabase(database);
return factory;
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate template = new RedisTemplate<>();
RedisSerializer stringSerializer = new StringRedisSerializer();//序列化为String
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//序列化为Json
template.setKeySerializer(stringSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//set value serializer
template.setDefaultSerializer(jackson2JsonRedisSerializer);
template.setConnectionFactory(jedisConnectionFactory());
template.afterPropertiesSet();
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//自定义key前缀
CacheKeyPrefix cacheKeyPrefix = new CacheKeyPrefix() {
@Override
public String compute(String cacheName) {
return cacheName+":";
}
};
//设置CacheManager的值序列化方式为json序列化
RedisSerializer
配置类整合好,建立一个 redis 的工具类:(便于操作)
package com.community.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
return false;
}
}
public boolean setExpire(String key, Object value, long expire) {
try {
//TimeUnit.SECONDS指定类型为秒
redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
return true;
} catch (Exception e) {
return false;
}
}
public boolean expire(String key, long expire) {
try {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
return true;
} catch (Exception e) {
return false;
}
}
public long ttl(String key) {
return redisTemplate.getExpire(key);
}
public void del(String... keys) {
if (keys != null && keys.length > 0) {
redisTemplate.delete((Collection) CollectionUtils.arrayToList(keys));
}
}
public long incrBy(String key, long step) {
return redisTemplate.opsForValue().increment(key, step);
}
public boolean setNx(String key, Object value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
public boolean setNxAndExpire(String key, Object value, long expire) {
return redisTemplate.opsForValue().setIfAbsent(key, value, expire, TimeUnit.SECONDS);
}
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
}
配置完成,开始测试!
在 controller 层里写一个 demo 进行测试
@Resource
private RedisUtil redisUtil;
@RequestMapping("demo")
public ResultJson test() {
redisUtil.set("thx", "123");
System.out.println(redisUtil.get("thx"));
return null;
}
去 redis 查看数据,如果发现有 thx 的键值,说明测试成功,完成闭环



