大家都知道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.</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 { @Autowired
private 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); @Autowired
private 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().getName());
return user;
}
}
e.application.yml 配置如下(redis host,port,password,database 注意)
  #redis
redis:
#database:
host: 100.100.100.100
port:
password:
database:
pool:
max-idle:
min-idle:
max-active:
max-wait: -1
f. UserController.java 添加
    @Autowired
private UserRedisService userRedisService;
/**
* @Title: UserController
* @Description: 初始化redis数据
* @return
* @author mengfanzhu
* @throws
*/
@RequestMapping("/initRedisdata")
@ResponseBody
public String initRedisData(){
userRedisService.redisInitData();
return "success";
}
@RequestMapping("/getUserRedisByLoginName/{loginName}")
@ResponseBody
public 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().getName());
return result;
}

3.运行效果

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

b.查看redis

c.浏览器查看数据

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

SpringBoot实践 - SpringBoot+MySql+Redis的更多相关文章

  1. SpringBoot实践 - SpringBoot+mysql

    关于springBoot是个神马东西以及优缺点,请自行搜索了解. LZ看到很多关于SpringBoot的Demo,单看一篇总是没法整合SpringBoot与Mysql.没法子,还是自己操刀来一发为妙. ...

  2. 基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【六】【引入bootstrap前端框架】

    https://blog.csdn.net/linzhefeng89/article/details/78752658 基于springboot+bootstrap+mysql+redis搭建一套完整 ...

  3. Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket

    https://blog.csdn.net/a123demi/article/details/78234023  : Springboot集成mybatis(mysql),mail,mongodb,c ...

  4. IDEA SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统

    先放上github地址:spike-system,可以直接下载完整项目运行测试 SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统 技术栈:SpringBoot, MyS ...

  5. Shiro整合springboot,freemaker,redis(含权限系统完整源码)

    区块链技术联盟 2018-02-08 17:06:40 目录 一.导语 二.shiro功能介绍 三.shiro详解 四.shiro实战案例分享 五.系统配置 六.其他 一.导语 今天推荐给大家一个非常 ...

  6. 【springBoot】springBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  7. Springboot+Atomikos+Jpa+Mysql实现JTA分布式事务

    1 前言 之前整理了一个spring+jotm实现的分布式事务实现,但是听说spring3.X后不再支持jotm了,jotm也有好几年没更新了,所以今天整理springboot+Atomikos+jp ...

  8. Java逆向工程SpringBoot + Mybatis Generator + MySQL

    Java逆向工程SpringBoot+ Mybatis Generator + MySQL Meven pop.xml文件添加引用: <dependency> <groupId> ...

  9. Springboot 2.0 - 集成redis

    序 最近在入门SpringBoot,然后在感慨 SpringBoot较于Spring真的方便多时,顺便记录下自己在集成redis时的一些想法. 1.从springboot官网查看redis的依赖包 & ...

随机推荐

  1. python实现断点续传下载文件

    最近的任务里有一个功能是要我从日志服务器实时跟新日志到本地,日志在不断新增内容就需要我隔一段时间从上次下载的位置继续下载,并写入本地文件上次写完的位置后面. headers = {'Range': ' ...

  2. mysql 常用指令

    修改表的字符集 88down voteaccepted If you want to change the table default character set and all character ...

  3. UVa 11495 - Bubbles and Buckets

    题目大意:给一个有n个数的序列,通过交换相邻的逆序数使这个序列最终有序,求需要交换的次数. 本来可以用冒泡排序解决,但是n达到105,用冒泡排序会超时,用O(nlogn)的归并排序可以达到要求.< ...

  4. 使用命令创建github代码仓库,push本地仓库到github远程代码仓库

    1.利用命令创建github远程代码仓库 在将本地代码push到github远程代码仓库之前,总是需要新建github代码仓库,在将本地仓库关联到github远程仓库.其中最为繁琐的操作是建立gith ...

  5. 手动写一个Servlet

    一.做一个类,派生自HttpServlet 1.导两个包 javax.servlet.*; javax.servlet.http.* 2.重写两个方法doGet,doPost 打开tomcat中的se ...

  6. 1.4.2.3. SETUP(Core Data 应用程序实践指南)

    初始化Core Data的三个方法: init,初始化托管对象模型.持久化存储协调器.托管对象上下文 - (id)init { ) { NSLog(@"Running %@ '%@'&quo ...

  7. tomcat 错误查看

    路径 : \tomcat\logs 清除日志,重新启动生成 从上到下,依次查看错误,可以看到,上面的两个是系统的启动模块.然后第三行错误提示,明显指出了错误原因 “NoClassDefFoundErr ...

  8. js判断浏览器在PC中打开还是移动设备中打开

    var browser = {                            versions: function () {                                va ...

  9. java Swing 图片缓冲机制

    java Swing 图片缓冲机制: 参考:http://jorneyr.iteye.com/blog/868858#comments package util; import java.awt.ge ...

  10. nodejs 中使用 mocha + should + jscoverage 生成 单元测试覆盖率报告

    最近一直在做nodejs,而关于js的单元测试覆盖率网上资料比较少而且吧比较零散,我从网上找来一些资料整理一下分析给大家,希望大家可以少走弯路. 首先我是从windows环境下测试的,用到的工具有 m ...