大家都知道redis的强大之处,在目前应用上也是大显神威。

先说说他的优点:

1 读写性能优异

2 支持数据持久化,支持AOF日志和RDB快照两种持久化方式

3 支持主从复制,主机会自动将数据同步到从机,可以进行读写分离。

4 数据结构丰富:除了支持string类型的value外还支持string、hash、set、sortedset、list等数据结构。

那么现在我们在 StringBoot+mysql的基础上引入Redis缓存中间件。

(关于SpringBoot+mysql的Demo可查看 SpringBoot+Mysql )

1.先看下完成后的代码结构

2. 操作如下

  a.在pom.xml引入如下依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.0</version></dependency>

  b.添加 RedisConfiguration.java
package com.example.config;import org.springframework.context.annotation.Bean;
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;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;/**
* @ClassName: RedisConfiguration
* @Description: Redis Config
* @author mengfanzhu
* @date 2017年2月21日 下午2:03:26
*/@Configuration
public class RedisConfiguration {@Bean@SuppressWarnings({ "rawtypes", "unchecked" })public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisFactory){StringRedisTemplate template = new StringRedisTemplate(redisFactory);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;}
}

c.添加  UserRedis.java
package com.example.service;import java.util.List;
import java.util.concurrent.TimeUnit;import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;import com.example.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;/**
* @ClassName: UserRedis
* @Description:  redis 提供5种数据类型的操作
* String ,hash ,list , set , zset
* @author mengfanzhu
* @date 2017年2月21日 下午2:01:43
*/
@Repository
public class UserRedis {@Autowiredprivate RedisTemplate<String, String> redisTemplate;public void addUser(String key,Long time,User user){Gson gson = new Gson();redisTemplate.opsForValue().set(key, gson.toJson(user),time,TimeUnit.MINUTES);}public void addUserList(String key,Long time,List<User> userList){Gson gson = new Gson();redisTemplate.opsForValue().set(key, gson.toJson(userList),time,TimeUnit.MINUTES);}public User getUserByKey(String key){Gson gson = new Gson();User user = null;String userJson = redisTemplate.opsForValue().get(key);if(StringUtils.isNotEmpty(userJson)){user =  gson.fromJson(userJson, User.class);}return user;}public List<User> getUserListByKey(String key){Gson gson = new Gson();List<User> userList = null;String userJson = redisTemplate.opsForValue().get(key);if(StringUtils.isNotEmpty(userJson)){userList =  gson.fromJson(userJson, new TypeToken<List<User>>(){}.getType()    );}return userList;}public void deleteByKey(String key){redisTemplate.opsForValue().getOperations().delete(key);}
}

d.添加 UserRedisService.java
package com.example.service;import java.util.ArrayList;
import java.util.Date;
import java.util.List;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.Assert;import com.example.config.RedisConfiguration;
import com.example.entity.Department;
import com.example.entity.Role;
import com.example.entity.User;/**
* @ClassName: UserRedisService
* @Description: user redis
* @author mengfanzhu
* @date 2017年2月21日 下午2:25:39
*/
@Service
@ContextConfiguration(classes = {RedisConfiguration.class,UserRedis.class} )
public class UserRedisService {private Logger logger = LoggerFactory.getLogger(UserRedisService.class);@Autowiredprivate UserRedis userRedis;public void redisInitData(){Department department = new Department();department.setName("科技部REDIS");Role role = new Role();role.setName("管理员REDIS");List<Role> roleList = new ArrayList<Role>();roleList.add(role);User user =new User();user.setName("管理员REDIS");user.setLoginName("adminRedis");user.setCreatedate(new Date());user.setRoleList(roleList);user.setDepartment(department);logger.info("key:" + this.getClass().getName()+":userByLoginName:"+user.getLoginName());userRedis.deleteByKey(this.getClass().getName()+":userByLoginName:"+user.getLoginName());userRedis.addUser(this.getClass().getName()+":userByLoginName:"+user.getLoginName(),3600L,user);}public User getUserRedis(String loginName){User user = userRedis.getUserByKey(this.getClass().getName()+":userByLoginName:"+loginName);Assert.notNull(user,"用户为空!");logger.info("===user=== name:{},loginName: {},departmentName:{}, roleName:{}",user.getName(),user.getLoginName(),user.getDepartment().getName(),user.getRoleList().get(0).getName());return user;}
}

e.application.yml 配置如下(redis host,port,password,database 注意)
  #redisredis:#database:9host: 100.100.100.100port: 1234password: 1234database: 1pool:max-idle: 8min-idle: 0max-active: 8 max-wait: -1

f. UserController.java 添加
    @Autowiredprivate UserRedisService userRedisService;
/** * @Title: UserController* @Description: 初始化redis数据* @return  * @author mengfanzhu* @throws */@RequestMapping("/initRedisdata")@ResponseBodypublic String initRedisData(){userRedisService.redisInitData();return "success";}@RequestMapping("/getUserRedisByLoginName/{loginName}")@ResponseBodypublic Map<String,Object> getUserRedisByLoginName(@PathVariable String loginName){Map<String,Object> result = new HashMap<String, Object>();User user = userRedisService.getUserRedis(loginName);Assert.notNull(user);result.put("name", user.getName());result.put("loginName", user.getLoginName());result.put("departmentName",user.getDepartment().getName());result.put("roleName", user.getRoleList().get(0).getName());return result;}

3.运行效果

a.浏览器输入  localhost:9090/user/initRedisdata

b.查看redis

c.浏览器查看数据

代码已上传至 Github ,https://github.com/fzmeng/spring_boot_demo_hello

转载于:https://www.cnblogs.com/cnmenglang/p/6424236.html

SpringBoot实践 - SpringBoot+MySql+Redis相关推荐

  1. 基于javaweb的在线点餐系统(java+springboot+mybatis+vue+mysql+redis)

    基于javaweb的在线点餐系统(java+springboot+mybatis+vue+mysql+redis) 运行环境 Java≥8.MySQL≥5.7.Node.js≥10 开发工具 后端:e ...

  2. SpringBoot+Maven+MyBaitsPlus+MySQL+Redis——配置、开启Redis的基本使用

    1.前置知识 (1)MybatisPlus操作数据库与代码生成:有道云笔记 2.安装RDIS监控软件:RedisDesktopManager 3.引入pom.xml引入依赖 <dependenc ...

  3. mybatis redis_SpringBoot + Mybatis + Shiro + mysql + redis智能平台源码分享

    后端技术栈 基于 SpringBoot + Mybatis + Shiro + mysql + redis构建的智慧云智能教育平台 基于数据驱动视图的理念封装 element-ui,即使没有 vue ...

  4. ubuntu系统下安装docker并部署Springboot+mysql+redis

    目录 安装Docker Docker常用命令 构建mysql容器 构建Redis容器 构建Springboot应用镜像及容器 (1)springboot使用maven将程序打成jar包,接着编写Dok ...

  5. Shiro教程_2 Shiro+SpringBoot+Mysql+Redis(缓存)

    源代码 https://gitee.com/fakerlove/Shiro Shiro+SpringBoot+Mysql+Redis(缓存) 1. 添加依赖 <?xml version=&quo ...

  6. 基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【八】【完善整个项目】

    上一章我们已经完成了菜单模块的开发工作,那么到了本章我们将完成我们角色管理模块的开发工作,在本章开始一个全新的模块进行开发的时候我们需要遵守一定的命名和开发规范如下: 1.我们的Controller的 ...

  7. 在Docker 上完成对Springboot+Mysql+Redis的前后端分离项目的部署(全流程,全截图)

    本文章全部阅读大约2小时,包含一个完整的springboot + vue +mysql+redis前后端分离项目的部署在docker上的全流程,比较复杂,请做好心理准备,遇到问题可留言或则私信 目录 ...

  8. 基于javaweb的进销存管理系统(前后端分离+java+vue+springboot+ssm+mysql+redis)

    基于javaweb的进销存管理系统(前后端分离+java+vue+springboot+ssm+mysql+redis) 运行环境 Java≥8.MySQL≥5.7.Node.js≥10 开发工具 后 ...

  9. 基于javaweb的课程自动排课系统(java+springboot+html+layui+thymeleaf+redis+mysql)

    基于javaweb的课程自动排课系统(java+springboot+html+layui+thymeleaf+redis+mysql) 运行环境 Java≥8.MySQL≥5.7 开发工具 ecli ...

最新文章

  1. 在内核中增加对yaffs文件系统的支持
  2. 32位oracle_Oracle 之Hugepage
  3. Firefox 44.0将在Linux上启用H.264支持:GTK3仍缺席
  4. 【题意+分析】1043 Is It a Binary Search Tree (25 分)
  5. 华为 鸿蒙 升级,华为鸿蒙系统已陆续推送!安卓系统可无缝升级:升级包容量高达6GB...
  6. 华为笔试题-磁盘容量排序
  7. 怎么配置宝塔linux环境,宝塔面板linux怎么安装
  8. 联想电脑摄像头亮灯却无法正常显示解决
  9. 成功之路散文连载之名师出高徒
  10. CocosStudio(八)AtlasLabel数字标签、BitmapLabel自定义字体、Label文本框
  11. 关键词优化推广需要怎么做?有哪些方法和技巧
  12. poscms多语言网站方案
  13. 十步会用IOCOMP–iplotx控件
  14. 关于XUL上的textbox中的persist属性使用
  15. 中式客厅装修的特点 亦古亦今的惊艳每一家
  16. Docker - 使用Docker Compose部署应用
  17. 不是python内置函数的是_Python内置函数
  18. HDU 2047 [阿牛的EOF牛肉串] 递推
  19. Minic III介绍
  20. 电影里的超级计算机,宇宙终极答案“42”到底是什么意思?超级计算机为我们揭晓答案...

热门文章

  1. ext教程_exe_作者blackant
  2. c++学习笔记(7) 面向对象思想
  3. 索引超出了数组界限_【每天一题】LeetCode 26. 删除排序数组中的重复项
  4. mysql实现知识图谱_基于电影知识图谱的智能问答系统学习记录
  5. char强制类型转换为int_为强制类型转换正名
  6. 北京链安:火币生态链Heco主网上线一月,已达到以太坊峰值5倍处理能力
  7. Cover团队在Kovan以太坊测试网部署xCOVER智能合约
  8. SAP 产品部署方式及定价模型
  9. SAP License:SAP中的产量法折旧计算
  10. 风控算法知识——WOE值的深度理解与应用