// 前提已经配置好了springboot依赖
// 引入Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
使用 的是application.yml依赖 配置部分
server:
port: 8080
# redis
redis:
# redis数据库索引(默认为0)
database: 0
# redis服务器地址(默认为loaclhost)
host: 127.0.0.1
# redis端口(默认为6379)
port: 6379
# redis访问密码(默认为空)
password:
# redis连接超时时间(单位毫秒)
timeout: 2000
jedis:
# redis连接池配置
pool:
# 最大可用连接数(默认为8,负数表示无限)
max-active: 200
# 最大空闲连接数(默认为8,负数表示无限)
max-idle: 10
# 最小空闲连接数(默认为0,该值只有为正数才有用)
min-idle: 20
# 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限)
// 创建代理
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);
jacksonSeial.setObjectMapper(objectMapper);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
}
//
@RequestMapping(value = "/Test002", method = RequestMethod.GET)
public Object Test002() throws Exception {
redisTemplate.opsForValue().set("111", "value的值");
//从缓存中拿到数据
Object o = redisTemplate.opsForValue().get("111");
System.out.println(o);
return o;
}