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