1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置文件
# redis
spring.redis.host=localhost
spring.redis.database=0
spring.redis.port=6379
spring.redis.password=
3、配置类
package com.shenmazong.send.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;
/**
* @author 军哥
* @version 1.0
* @description: 配置自定义redisTemplate
* @date 2022/2/9 11:23
*/
@Configuration
@EnableCaching
public class RedisConfig {
/**
* 配置自定义redisTemplate
* @return
*/
@Bean
RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// 设置值(value)的序列化采用Jackson2JsonRedisSerializer。
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
4、测试类
package com.shenmazong.send;
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 java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class ServerShopSendApplicationTests {
@Autowired
RedisTemplate redisTemplate;
@Test
void testRedis() {
ArrayList<String> names = new ArrayList<>();
names.add("zhangsan");
names.add("李四");
redisTemplate.opsForValue().set("hello", names, 60, TimeUnit.MINUTES);
//
Object hello = redisTemplate.opsForValue().get("hello");
System.out.println(hello);
}
}