github地址:https://github.com/AndyFlower/Spring-Boot-Learn/tree/master/spring-boot-nosql-redis
一、加入依赖到pom.xml
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency> 5 <!--转换json数据格式的数据--> 6 <dependency> 7 <groupId>com.google.code.gson</groupId> 8 <artifactId>gson</artifactId> 9 </dependency>
二、创建Redis服务类
Redis提供了下列几种数据类型可以存取
- String
- hash
- list
- set和zset
在Spring Boot中没有提供像JPA那样的资源库接口,我们自定义一个User的服务类。
1 package com.slp.repository; 2 3 import com.google.gson.Gson; 4 import com.google.gson.reflect.TypeToken; 5 import com.slp.entity.User; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.data.redis.core.RedisTemplate; 8 import org.springframework.stereotype.Repository; 9 import org.springframework.util.StringUtils; 10 11 import java.util.List; 12 import java.util.concurrent.TimeUnit; 13 14 /** 15 * Created by sangliping on 2017/8/18. 16 */ 17 @Repository 18 public class UserRedis { 19 @Autowired 20 private RedisTemplate<String,String> redisTemplate; 21 public void add(String key,Long time,User user){ 22 Gson gson = new Gson(); 23 redisTemplate.opsForValue().set(key,gson.toJson(user),time, TimeUnit.MINUTES); 24 } 25 26 27 public void add(String key, Long time, List<User> users){ 28 Gson gson = new Gson(); 29 redisTemplate.opsForValue().set(key,gson.toJson(users),time,TimeUnit.MINUTES); 30 } 31 32 33 public User get(String key){ 34 Gson gson = new Gson(); 35 User user = null; 36 String userJson = redisTemplate.opsForValue().get(key); 37 if(!StringUtils.isEmpty(userJson)){ 38 user = gson.fromJson(userJson,User.class); 39 } 40 return user; 41 } 42 43 public List<User> getList(String key){ 44 Gson gson = new Gson(); 45 List<User> lu = null; 46 String listjson = redisTemplate.opsForValue().get(key); 47 if(!StringUtils.isEmpty(listjson)){ 48 lu = gson.fromJson(listjson,new TypeToken<List<User>>(){}.getType()); 49 } 50 return lu; 51 } 52 53 public void delete (String key){ 54 redisTemplate.opsForValue().getOperations().delete(key); 55 } 56 }
因为Redis没有表结构的概念,所以要实现MySql数据库中标的数据在Redis中存取,需要做一些转换,这里我们使用了Gson,将对象转换为JSON格式的文本进行存储,取出数据时再将JSON文本数据转换为Java对象。
Redis使用了key-value的方式存储数据,所以在存入时要生成一个唯一的key,而要查询或删除的时候就使用这个唯一的key进行操作。
默认情况下Redis中的数据是永久存储的,可以指定生命周期来进行控制。
要想正确的调用RedisTemplate需要做一些初始化工作,即对它存取的字符串进行一个JSON格式的系列化初始配置(此处没有注入因为测试也有一个配置文件都注入会冲突,正式的时候这里要注入)
1 package com.slp.config; 2 3 import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 import com.fasterxml.jackson.annotation.PropertyAccessor; 5 import com.fasterxml.jackson.databind.ObjectMapper; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.data.redis.connection.RedisConnectionFactory; 8 import org.springframework.data.redis.core.RedisTemplate; 9 import org.springframework.data.redis.core.StringRedisTemplate; 10 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 11 12 /** 13 * Created by sangliping on 2017/8/18. 14 */ 15 16 public class RedisConfig { 17 public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){ 18 StringRedisTemplate template = new StringRedisTemplate(factory); 19 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 20 ObjectMapper om = new ObjectMapper(); 21 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 22 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 23 jackson2JsonRedisSerializer.setObjectMapper(om); 24 template.setValueSerializer(jackson2JsonRedisSerializer); 25 template.afterPropertiesSet(); 26 return template; 27 } 28 }
三、测试准备
1、参数配置
1 spring.datasource.url=jdbc:mysql://localhost:3306/dev?characterEncoding=utf-8 2 spring.datasource.username=root 3 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 4 spring.datasource.password=123456 5 spring.jpa.database=mysql 6 spring.jpa.show-sql=true 7 spring.jpa.hibernate.ddl-auto=update 8 spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy 9 spring.jpa.propertie.hibernate.dialect=org.hibernate.dialect.MySQLDialect 10 spring.redis.database=1 11 spring.redis.host=localhost 12 spring.redis.port=6379 13 spring.redis.pool.max-idle=8 14 spring.redis.pool.min-idle=0 15 spring.redis.pool.max-active=8 16 spring.redis.pool.max-wait=-1
2、编写测试类
1 package com.slp; 2 3 import com.slp.entity.Department; 4 import com.slp.entity.Role; 5 import com.slp.entity.User; 6 import com.slp.repository.UserRedis; 7 import org.junit.Before; 8 import org.junit.Test; 9 import org.junit.runner.RunWith; 10 import org.slf4j.Logger; 11 import org.slf4j.LoggerFactory; 12 import org.springframework.beans.factory.annotation.Autowired; 13 import org.springframework.test.context.ContextConfiguration; 14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 16 import java.util.ArrayList; 17 import java.util.Date; 18 import java.util.List; 19 20 21 /** 22 * Created by sangliping on 2017/8/18. 23 */ 24 @RunWith(SpringJUnit4ClassRunner.class) 25 @ContextConfiguration(classes = {RedisConfig.class, UserRedis.class}) 26 public class RedisTest { 27 private static Logger logger = LoggerFactory.getLogger(RedisTest.class); 28 @Autowired 29 UserRedis userRedis; 30 31 @Before 32 public void setup(){ 33 Department department = new Department(); 34 department.setName("设计部"); 35 36 Role role = new Role(); 37 role.setName("admin"); 38 39 User user = new User(); 40 user.setName("slp"); 41 user.setCreatedate(new Date()); 42 user.setDeparment(department); 43 44 List<Role> roles = new ArrayList<Role>(); 45 roles.add(role); 46 47 user.setRoles(roles); 48 userRedis.delete(this.getClass().getName()+":userByName:"+user.getName()); 49 userRedis.add(this.getClass().getName()+":userByName:"+user.getName(),10L,user); 50 51 52 } 53 @Test 54 public void get(){ 55 User u = userRedis.get(this.getClass().getName()+":userByName:user"); 56 } 57 }
3、配置测试变量
1 package com.slp; 2 3 import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 import com.fasterxml.jackson.annotation.PropertyAccessor; 5 import com.fasterxml.jackson.databind.ObjectMapper; 6 import org.springframework.context.annotation.Bean; 7 import org.springframework.context.annotation.Configuration; 8 import org.springframework.data.redis.connection.RedisConnectionFactory; 9 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 10 import org.springframework.data.redis.core.RedisTemplate; 11 import org.springframework.data.redis.core.StringRedisTemplate; 12 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 13 14 /** 15 * Created by sangliping on 2017/8/18. 16 */ 17 @Configuration 18 public class RedisConfig { 19 @Bean 20 public JedisConnectionFactory jedisConnectionFactory(){ 21 JedisConnectionFactory factory = new JedisConnectionFactory(); 22 factory.setHostName("127.0.0.1"); 23 factory.setPort(6379); 24 return factory; 25 } 26 27 @Bean 28 public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){ 29 StringRedisTemplate template = new StringRedisTemplate(factory); 30 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 31 ObjectMapper om = new ObjectMapper(); 32 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 33 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 34 jackson2JsonRedisSerializer.setObjectMapper(om); 35 template.setValueSerializer(jackson2JsonRedisSerializer); 36 template.afterPropertiesSet(); 37 return template; 38 } 39 }