大家都知道redis的强大之处,在目前应用上也是大显神威。
先说说他的优点:
1 读写性能优异
2 支持数据持久化,支持AOF日志和RDB快照两种持久化方式
3 支持主从复制,主机会自动将数据同步到从机,可以进行读写分离。
4 数据结构丰富:除了支持string类型的value外还支持string、hash、set、sortedset、list等数据结构。
那么现在我们在 StringBoot+mysql的基础上引入Redis缓存中间件。
(关于SpringBoot+mysql的Demo可查看SpringBoot+Mysql )
1.先看下完成后的代码结构
2. 操作如下
a.在pom.xml引入如下依赖
org.springframework.boot
spring-boot-starter-data-redis
com.google.code.gson
gson
2.8.
b.添加 RedisConfiguration.java
package com.example.config;
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;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @ClassName: RedisConfiguration
* @Description: Redis Config
* @author mengfanzhu
* @date 2017年2月21日 下午2:03:26
*/
@Configuration
public class RedisConfiguration {
@Bean
@SuppressWarnings({ "rawtypes", "unchecked" })
public RedisTemplate redisTemplate(RedisConnectionFactory redisFactory){
StringRedisTemplate template = new StringRedisTemplate(redisFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jacks