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的更多相关文章

  1. spring boot 2.x 系列 —— spring boot 整合 redis

    文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...

  2. 微软BI 之SSIS 系列 - 在 SSIS 中导入 ACCESS 数据库中的数据

    开篇介绍 来自 天善学院 一个学员的问题,如何在 SSIS 中导入 ACCESS 数据表中的数据. 在 SSIS 中导入 ACCESS 数据库数据 ACCESS 实际上是一个轻量级的桌面数据库,直接使 ...

  3. NoSql数据库Redis系列(1)——Redis简介

    一.redis介绍 (一).Redis 简介 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点 ...

  4. spring boot 2.x 系列 —— spring boot 实现分布式 session

    文章目录 一.项目结构 二.分布式session的配置 2.1 引入依赖 2.2 Redis配置 2.3 启动类上添加@EnableRedisHttpSession 注解开启 spring-sessi ...

  5. spring boot 2.x 系列 —— spring boot 整合 dubbo

    文章目录 一. 项目结构说明 二.关键依赖 三.公共模块(boot-dubbo-common) 四. 服务提供者(boot-dubbo-provider) 4.1 提供方配置 4.2 使用注解@Ser ...

  6. spring boot 2.x 系列 —— spring boot 整合 druid+mybatis

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.说明 1.1 项目结构 项目查询用的表对应的建表语句放置在resour ...

  7. spring boot 2.x 系列 —— spring boot 整合 servlet 3.0

    文章目录 一.说明 1.1 项目结构说明 1.2 项目依赖 二.采用spring 注册方式整合 servlet 2.1 新建过滤器.监听器和servlet 2.2 注册过滤器.监听器和servlet ...

  8. spring boot 2.x 系列 —— spring boot 整合 RabbitMQ

    文章目录 一. 项目结构说明 二.关键依赖 三.公共模块(rabbitmq-common) 四.服务消费者(rabbitmq-consumer) 4.1 消息消费者配置 4.2 使用注解@Rabbit ...

  9. spring boot 2.x 系列 —— spring boot 整合 kafka

    文章目录 一.kafka的相关概念: 1.主题和分区 2.分区复制 3. 生产者 4. 消费者 5.broker和集群 二.项目说明 1.1 项目结构说明 1.2 主要依赖 二. 整合 kafka 2 ...

随机推荐

  1. jQuery Validation让验证变得如此easy(二)

    上一个样例我们是统一引用jquery.validate.js这样全部必填字段的提示信息都将是This field is required. 如今要改成动态提示,比方姓名假设为空则提示姓名不能为空,密码 ...

  2. at 命令

    每天什么时候执形at 12:00 /every:Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday shutdown -r

  3. 定时任务quartz与spring的集成

    我想要在spring的集成框架中使用spring , 暂时采用quartz 根据下面的几篇博客实现了(懒得说了,直接丢链接): Quartz实现动态定时任务 Spring 3整合Quartz 2实现定 ...

  4. 惊艳的HTML5动画特效及源码

    今天我们要来分享一些很酷的HTML5动画演示,HTML5的强大之处在于它可以利用canvas的特性来绘制很多普通网页无法完成的图形和动画,canvas就像一块超级画板,在上面不仅可以实现平面图形,而且 ...

  5. Oracle 一个中文汉字 占用几个字节,由Oracle中字符集编码决定

    Oracle 一个中文汉字 占用几个字节,要根据Oracle中字符集编码决定 查看oracle server端字符集 select userenv('language') from dual; 如果显 ...

  6. [Learn AF3]第五章 App Framework 3组件之Drawer——Side Menu

    Drawer——Side menu 组件名称:Drawer     说明:af3中的side menu和af2中有很大变化,af3中的side menu实际上是通过插件$.afui.drawer来实现 ...

  7. maven添加本地jar到本地库中

    maven添加本地jar到本地库中(用于远端地址下载不了的情况) 在dos命令行执行以下命令将会吧ojdbc14-10.2.0.4.0.jar添加到本地库中(ps:必须已经安装了,maven,并配置了 ...

  8. RancherOS(ROS)如何安装到硬盘? 并设置为用户自动登录到系统? -a rancher.autologin=tty1

    RancherOS 安装到硬盘,一般都是通过ssh_authorized_keys 方式. ------------------------------------------- 从第一次认识到这个方 ...

  9. Git项目协同开发学习笔记1:项目库开发基础git命令

    这年头git基本都是项目开发的标配,之前刚好碰到了就花了两天时间系统学习了下.本文内容基本来自以下tutorial:Learn Git(建议直接去看原文,因为这个网站是有更新的).这个是我看过对git ...

  10. redis队列操作

    PHP版: <?php /** * Redis * 配置 $redis_host,$redis_port * 队列操作 * @author win 7 */ class RQueue{ priv ...