linux拉取dokcer镜像
docker pull redis
主目录创建文件夹做redis的映射,这里先创建是因为docker不存在redis.conf
如果直接映射会当作目录而不是文件
mkdir -p /mydata/redis/conf touch /mydata/redis/conf/redis.conf
根据镜像创建容器 建议修改映射端口这把修改问9736
docker run -p 9736:6379 --name redis -v /mydata/redis/data:/data \ -v/mydata/redis/conf/redis.conf:/etc/redis/redis.conf \ -d redis redis-server /etc/redis/redis.conf
使用RedisDesktopManager,测试连接
redis完成
使用Java操作redis
maven导入依赖
<!-- spring boot redis缓存引入 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 缓存连接池--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!-- redis 存储 json序列化 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
yml添加配置
spring: redis: host: 192.168.100.100 port: 6379 database: 0 password: 123456 #默认为空 timeout: 3000ms #最大等待时间,超时则抛出异常,否则请求一直等待 lettuce: pool: max-active: 20 #最大连接数,负值表示没有限制,默认8 max-wait: -1 #最大阻塞等待时间,负值表示没限制,默认-1 max-idle: 8 #最大空闲连接,默认8 min-idle: 0 #最小空闲连接,默认0
测试存入
package com.atguigu.srb.core; @SpringBootTest @RunWith(SpringRunner.class) public class RedisTemplateTests { @Resource private RedisTemplate redisTemplate; @Resource private DictMapper dictMapper; @Test public void saveDict(){ Dict dict = dictMapper.selectById(1); //向数据库中存储string类型的键值对, 过期时间5分钟 redisTemplate.opsForValue().set("dict", dict, 5, TimeUnit.MINUTES); } }
使用json序列化
@Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); //首先解决key的序列化方式 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); //解决value的序列化方式 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); //序列化时将类的数据类型存入json,以便反序列化的时候转换成正确的类型 ObjectMapper objectMapper = new ObjectMapper(); //objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); // 解决jackson2无法反序列化LocalDateTime的问题 objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.registerModule(new JavaTimeModule()); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); return redisTemplate; } }
重新存入
取值测试
@Test public void getDict(){ Dict dict = (Dict)redisTemplate.opsForValue().get("dict"); System.out.println(dict); }