【Spring Boot&&Spring Cloud系列】Spring Boot中使用NoSql数据库Redis
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;
}
}
4、执行完成redis中数据
【Spring Boot&&Spring Cloud系列】Spring Boot中使用NoSql数据库Redis的更多相关文章
- spring boot 2.x 系列 —— spring boot 整合 redis
文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...
- 微软BI 之SSIS 系列 - 在 SSIS 中导入 ACCESS 数据库中的数据
开篇介绍 来自 天善学院 一个学员的问题,如何在 SSIS 中导入 ACCESS 数据表中的数据. 在 SSIS 中导入 ACCESS 数据库数据 ACCESS 实际上是一个轻量级的桌面数据库,直接使 ...
- NoSql数据库Redis系列(1)——Redis简介
一.redis介绍 (一).Redis 简介 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点 ...
- spring boot 2.x 系列 —— spring boot 实现分布式 session
文章目录 一.项目结构 二.分布式session的配置 2.1 引入依赖 2.2 Redis配置 2.3 启动类上添加@EnableRedisHttpSession 注解开启 spring-sessi ...
- spring boot 2.x 系列 —— spring boot 整合 dubbo
文章目录 一. 项目结构说明 二.关键依赖 三.公共模块(boot-dubbo-common) 四. 服务提供者(boot-dubbo-provider) 4.1 提供方配置 4.2 使用注解@Ser ...
- spring boot 2.x 系列 —— spring boot 整合 druid+mybatis
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.说明 1.1 项目结构 项目查询用的表对应的建表语句放置在resour ...
- spring boot 2.x 系列 —— spring boot 整合 servlet 3.0
文章目录 一.说明 1.1 项目结构说明 1.2 项目依赖 二.采用spring 注册方式整合 servlet 2.1 新建过滤器.监听器和servlet 2.2 注册过滤器.监听器和servlet ...
- spring boot 2.x 系列 —— spring boot 整合 RabbitMQ
文章目录 一. 项目结构说明 二.关键依赖 三.公共模块(rabbitmq-common) 四.服务消费者(rabbitmq-consumer) 4.1 消息消费者配置 4.2 使用注解@Rabbit ...
- spring boot 2.x 系列 —— spring boot 整合 kafka
文章目录 一.kafka的相关概念: 1.主题和分区 2.分区复制 3. 生产者 4. 消费者 5.broker和集群 二.项目说明 1.1 项目结构说明 1.2 主要依赖 二. 整合 kafka 2 ...
随机推荐
- gradle 的安装
前言: 我不是一个勤奋好学的人,奔着新技术就跑去尝试学习.但是在工作或者学习的过程中,遇到了的技术,还是得一个坎一个坎的迈过去.把今天遇到的坎变成明天的垫脚石. 想学习一下 spring 的源码,然后 ...
- scala实现相邻两个元素挑换位置的代码,哈哈
import scala.math._ import breeze.plot._ import breeze.linalg._ import scala.collection.mutable.Arra ...
- result源码
CREATE TABLE `result` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,`thetime` CHAR(100) , `category ...
- 关于SpringMVC的文件上传
关于文件的上传,之前写过2篇文章,基于Struts2框架,下面给出文章链接: <关于Struts2的文件上传>:http://www.cnblogs.com/lichenwei/p/392 ...
- require.js初试(with angular & optimization)
如果你只是想找一款称手的js加载器,可以参考这篇js loader benchmarks(http://artzstudio.com/files/Boot/test/benchmarks/script ...
- Data Set Config配置元件
右键点击Jmeter中需要参数化的某个请求,选择添加——配置原件——CSV Data Set Config,会添加一个CSV Data Set Config,需要设置相关的一些内容,具体如下:
- level1 - unit 1 - 句子结构
preface 学习英语做为一种爱好,就是希望有一天能够和老外流畅沟通,目前来看,日常沟通还是没有问题的和我的外教. 知识日积月累,现在就把以前学习的(从初中到现在)知识总结下.每天一更,更到单元总结 ...
- VC获得本机网络连接状态
/本机网络连接类型(成功) #define NET_TYPE_RAS_DIAL_UP_CONNECT_NET 0x01 //上网类型:采用RAS拨号连接上网 0x01 ...
- nodejs的package.json
package.json文件会描述这个NPM包的所有相关信息,包括作者.简介.包依赖.构建等信息,格式是严格的JSON格式 在E:/nodejs/mychat下 执行,npm init 输入yes,就 ...
- Ubuntu14.04 安装git
通过ubuntu的APT安装 sudo apt-get update sudo apt-get install git 配置自己的Git账号信息 git config --global user.na ...