springboot整合redis(简单整理)

时间:2021-04-27 17:11:48

Redis安装与开启

  我这里是在windows上练习,所以这里的安装是指在windows上的安装,操作非常简单,点击https://github.com/MicrosoftArchive/redis/releases网址,直接点击下载解压就安装成功。开启也很简单:

  1.打开cmd,进入安装目录,输入命令:

redis-server.exe redis.windows.conf

  2.接着新打开一个cmd,原先的cmd不要关闭,不然后续步骤会出错,接着输入命令:

redis-cli.exe -h localhost -p 6379

  到这里windows上的redis已经安装并打开,可以正常使用了。

springboot整合redis

  1. 添加依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  2.配置redis

#redis配置
spring:
redis:
database: 0
host: localhost
port: 6379
password:

3.操作redis需要使用RedisTemplate这个对象,但是需要修改RedisTemplate对象的序列化方式。

SDR(spring data redis)默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
StringRedisTemplate默认采用String的序列化策略
RedisTemplate默认采用JDK的序列化策略
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; @Configuration
public class RedisConfiguration { @Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jsonRedisSerializer.setObjectMapper(mapper);
//值序列化
stringRedisTemplate.setValueSerializer(jsonRedisSerializer);
stringRedisTemplate.afterPropertiesSet();
return stringRedisTemplate;
}
}
3.简单测试操作redis:
@RunWith(SpringRunner.class)
@SpringBootTest
public class PsringbootdemoApplicationTests { private static final Logger logger = LoggerFactory.getLogger(PsringbootdemoApplicationTests.class); @Resource
RedisTemplate redisTemplate; @Test
public void testRedis(){
logger.info("测试redis");
redisTemplate.opsForValue().set("lll","sgf");
String value = (String) redisTemplate.opsForValue().get("lll");
System.out.println(value);
} }

结果如下:

springboot整合redis(简单整理)

springboot整合redis(简单整理)

RedisTemplate

  RedisTemplate中定义了对5种数据结构操作

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

具体的操作可以查看源码,或者推荐查看这篇博客Spring中使用RedisTemplate操作Redis(spring-data-redis)