【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 ...
随机推荐
- 嵌入式驱动开发之内核态spi ---module_spi_driver
http://blog.csdn.net/dearsq/article/details/51839083 http://blog.csdn.net/alleincao/article/details/ ...
- Kilo 版 Keystone 数据库结构
在安装完keystone并利用keystone-manage命令同步数据库后,mysql(我使用的存储后端)中新加了如下表: +------------------------+ | Tables_i ...
- python3 post方式上传文件。
借助第三方库:Requests 其官网地址: http://python-requests.org 官网上写的安装方式:http://docs.python-requests.org/ ...
- Linux 下 CPU 使用率与机器负载的关系与区别
原文链接: http://blog.chinaunix.net/uid-28541347-id-4926054.html 当我们使用top命令查看系统的资源使用情况时会看到load average, ...
- C# int转string 每三位加一个逗号
; Console.WriteLine(aaaa.ToString("N0")); Console.WriteLine()); Console.WriteLine("架构 ...
- scala分析数据作图
参考网址:https://stackoverflow.com/questions/36984780/spark-shell-how-to-use-breeze-viz 刚开始按照网上的教程只导入了 两 ...
- mysql 类型
1.bigint 范围(-2^63 (-9223372036854775808) 到 2^63-1 (9223372036854775807) ) 字节大小(8个字节) 2.int 范围(-2^31 ...
- UNIX环境编程学习笔记(6)——文件I/O之判断文件类型
lienhua342014-09-01 1 文件类型 我们平时最常接触的文件类型有普通文件(regular file)和目录(di-rectory file),但是 UNIX 系统提供了多种文件类型: ...
- koa中上传文件到阿里云oss实现点击在线预览和下载
比较好的在线预览的方法: 跳转一个新的页面,里面放一个iframe标签,或者object标签 <iframe src="xxx"></iframe> < ...
- 五大行获央行5000亿SLF 相当于降准0.5%
人民网北京9月17日电 (吕骞)据新浪财经报道,9月16日收盘后,市场传央行当天对五大行进行5000亿SLF操作,性质类同基础货币的投放,近似全面降准0.5个百分点.国泰君安.国信等数家机构晚间证实传 ...