Springboot整合redis

 

首先需自行安装redis数据库

springboot整合redis十分简单,只需要在application配置文件里配置:

spring:
  redis:
    host: localhost
    database: 0
    port: 6379
    timeout: 3000

即可通过注入redisTemplate操作redis数据库:

@Autowired
RedisTemplate redisTemplate;
@Test
public void set() {
	List<String> strList = Arrays.asList("a", "b", "c");
	redisTemplate.opsForValue().set("strList", strList);
}
@Test
public void get() {
	List<String> strList = (List<String>) redisTemplate.opsForValue().get("strList");
	strList.forEach(e -> System.out.println(e));
}
​

 这样就可以使用redis数据库了。但是使用命令行查看数据会有乱码类似"\xac\xed\x00\x05t\x00\astrList"。这是因为使用了默认的序列化。新增fastjson序列化配置RedisTemplate解决乱码。需引入fastjson依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.49</version>
</dependency>

这个类库有直接支持redis的FastJsonRedisSerializer


@Configuration
public class RedisConfig {
	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
                FastJsonRedisSerializer<Object> fastJsonRedisSerializer = 
                    new FastJsonRedisSerializer<Object>(Object.class);
		template.setKeySerializer(new  StringRedisSerializer());
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(fastJsonRedisSerializer);
		template.setHashValueSerializer(fastJsonRedisSerializer);
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值