1、在Maven pom.xml文件中加入Redis包
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${boot.version}</version> </dependency>
2、SpringBoot配置文件中配置Redis连接(YAML方式配置)默认是localhost:6379
#mybatis配置 mybatis: mapper-locations: classpath:mapper/*Mapper.xml type-aliases-package: com.carry.domain 数据源 spring: redis: host: 127.0.0.1 port: 6379
3、RedisTemplate 配置(RedisTemplate 实例化默认配置或需要按需配置后使用,StringRedisTemplate 则可以直接使用——继承自RedisTemplate)
package com.example.redis.demo; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; 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 public class RedisConfig { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } }
4、RedisTemplate的简单使用
package com.example.redis.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service public class RedisSave { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @PostConstruct public void find() { redisTemplate.opsForValue().set("users3", "1"); } }
opsForValue的作用是返回redis的操作命令,这里附上官方api解释:
opsForValue()
Returns the operations performed on simple values (or Strings in Redis terminology).
stringRedisTemplate 直接使用可以 查到 (users2),而
RedisTemplate直接使用则不可以(users3),需要配置后使用(配置后才可以)。