Springboot整合redis

步骤讲解

1、第一步jar导入:

      <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

如果你本地没有相应jar包,你可以在mevan存放jar包的库中,找到Setting文件,添加阿里云镜像,在跟新就可以下载相应jar包

       <mirror>
<id>alimaven-central</id>
<mirrorOf>central</mirrorOf>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
</mirror>

第二步:application.properties配置

            spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000 #=========redis线程池设置=========
# 连接池中的最大空闲连接,默认值也是8。
spring.redis.pool.max-idle=200 #连接池中的最小空闲连接,默认值也是0。
spring.redis.pool.min-idle=200 # 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active=2000 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
spring.redis.pool.max-wait=1000

配置

第三步创建实体

User类

import java.util.Date;

public class User {

    private int age;

    private String pwd;

    private String phone;

    private Date createTime;

    public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getPwd() {
return pwd;
} public void setPwd(String pwd) {
this.pwd = pwd;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public User() {
super();
} public User(int age, String pwd, String phone, Date createTime) {
super();
this.age = age;
this.pwd = pwd;
this.phone = phone;
this.createTime = createTime;
}
}

User类

JsonData工具类实体

/**
* 这是后端向前端响应的一个包装类
* 一般后端向前端传值会有三个属性
* 1:响应状态
* 2:如果响应成功,把数据放入
* 3: 描述,响应成功描述,或者失败的描述
*/
public class JsonData implements Serializable { private static final long serialVersionUID = 1L; private Integer code; // 状态码 0 表示成功,1表示处理中,-1表示失败
private Object data; // 数据
private String msg;// 描述 public JsonData() {
} public JsonData(Integer code, Object data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
} // 成功,只返回成功状态码
public static JsonData buildSuccess() {
return new JsonData(0, null, null);
} // 成功,传入状态码和数据
public static JsonData buildSuccess(Object data) {
return new JsonData(0, data, null);
} // 失败,传入描述信息
public static JsonData buildError(String msg) {
return new JsonData(-1, null, msg);
} // 失败,传入描述信息,状态码
public static JsonData buildError(String msg, Integer code) {
return new JsonData(code, null, msg);
} // 成功,传入数据,及描述信息
public static JsonData buildSuccess(Object data, String msg) {
return new JsonData(0, data, msg);
} // 成功,传入数据,及状态码
public static JsonData buildSuccess(Object data, int code) {
return new JsonData(code, data, null);
} //提供get和set方法,和toString方法
}

第四步创建工具类

1、字符串转对象,对象转字符串工具类

import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
* 字符串转对象,对象转字符串的工具类
* 因为StringRedisTemplate的opsForValue()方法需要key,value都需要String类型,所以当value值存入对象的时候
* 先转成字符串后存入。
*/
public class JsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); //对象转字符串
public static <T> String obj2String(T obj){
if (obj == null){
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} //字符串转对象
public static <T> T string2Obj(String str,Class<T> clazz){
if (StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

2、封装Redis类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component; /**
* 功能描述:redis工具类
* 对于redisTpl.opsForValue().set(key, value)进行了一次封装,不然每次都要这样保存值
* 而封装后只需:new RedisClient().set(key,value);
*/
@Component
public class RedisClient { @Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate // 功能描述:设置key-value到redis中
public boolean set(String key ,String value){
try{
redisTpl.opsForValue().set(key, value);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
} // 功能描述:通过key获取缓存里面的值
public String get(String key){
return redisTpl.opsForValue().get(key);
}
}

第五步创建Controller类

RdisTestController

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.jincou.model.JsonData;
import com.jincou.model.User;
import com.jincou.until.JsonUtils;
import com.jincou.until.RedisClient; @RestController
@RequestMapping("/api/v1/redis")
public class RdisTestController { //得到redis封装类
@Autowired
private RedisClient redis; //添加字符串
@GetMapping(value="add")
public Object add(){ redis.set("username", "xddddddd");
return JsonData.buildSuccess(); } //通过key值得到value字符串
@GetMapping(value="get")
public Object get(){ String value = redis.get("username");
return JsonData.buildSuccess(value); } //将对象通过工具类转成String类型,存入redis中
@GetMapping(value="save_user")
public Object saveUser(){
User user = new User(1, "abc", "11", new Date());
String userStr = JsonUtils.obj2String(user);
boolean flag = redis.set("base:user:11", userStr);
return JsonData.buildSuccess(flag); } //通过key值得到value值,让后将value转为对象
@GetMapping(value="find_user")
public Object findUser(){ String userStr = redis.get("base:user:11");
User user = JsonUtils.string2Obj(userStr, User.class);
return JsonData.buildSuccess(user); }
}

测试效果

命名规范:如果我们key按"base:user:11"这来命名,那么那么会自动创建文件夹格式,方便查看。


想太多,做太少,中间的落差就是烦恼。想没有烦恼,要么别想,要么多做。上尉【10】

springBoot(8)---整合redis的更多相关文章

  1. SpringBoot简单整合redis

    Jedis和Lettuce Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server. Jedis在实现上是直接连接的redis serve ...

  2. SpringBoot之整合Redis分析和实现-基于Spring Boot2.0.2版本

    背景介绍 公司最近的新项目在进行技术框架升级,基于的Spring Boot的版本是2.0.2,整合Redis数据库.网上基于2.X版本的整个Redis少之又少,中间踩了不少坑,特此把整合过程记录,以供 ...

  3. 【SpringBoot】整合Redis实战

    ========================9.SpringBoot2.x整合Redis实战 ================================ 1.分布式缓存Redis介绍 简介: ...

  4. SpringBoot学习(七)—— springboot快速整合Redis

    目录 Redis缓存 简介 引入redis缓存 代码实战 Redis缓存 @ 简介 redis是一个高性能的key-value数据库 优势 性能强,适合高度的读写操作(读的速度是110000次/s,写 ...

  5. 完整SpringBoot Cache整合redis缓存(二)

    缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...

  6. SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  7. SpringBoot之整合Redis

    一.SpringBoot整合单机版Redis 1.在pom.xml文件中加入redis的依赖 <dependency> <groupId>org.springframework ...

  8. springboot下整合redis使用redisTemplate模板

    pom <!-- 引入 redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupI ...

  9. springboot+JPA 整合redis

    1.导入redis依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifact ...

随机推荐

  1. Filezilla server配置FTP服务器中的各种问题与解决方法

    转至;https://www.jb51.net/article/122171.htm 安装文件以及补丁下载 公司很多资料需要通过ftp上传,那么就需要配置一个FTP服务器,找了一台Windows服务器 ...

  2. Asp.net Zero 应用实战-最初部署问题

    此时用的是aspnet-zero-core-4.3.0 1.前两天vs2017刚刚最新升级了,打开后就报错,然后就根据提示把每个项目文件中添加了 <PropertyGroup> <E ...

  3. python3中 tkinter模块创建window窗体、添加按钮、事务处理、创建菜单等的使用

    开始接触桌面图形界面编程,你可以到安装路径  \lib\tkinter 打开__init__.py 文件了解tkinter 1    tkinter 模块创建窗体,代码如下截图: 运行结果,如有右图显 ...

  4. kali自定义分辨率(1920*1080)

    运行一下两行代码: xrandr --newmode -hsync +vsync xrandr --addmode Virtual1 "1920x1080_60.00"

  5. Ajax基本语法

    案例代码: $(function(){ $('#send').click(function(){ $.ajax({ type: "GET", url: "test.jso ...

  6. 小白的CTF学习之路7——内存与硬盘

    前天去网吧跟朋友包宿,导致昨天一整天都报废,今天早上研究了一下nethunter导致手机成功变砖,感冒不停地咳嗽,这些理由应该足够我前两天拖更了吧,下面开始正题 磁盘学习路线 虚拟缓存 虚拟内存 节约 ...

  7. 2019.03.28 bzoj3325: [Scoi2013]密码(manacher+模拟)

    传送门 题意: 现在有一个nnn个小写字母组成的字符串sss. 然后给你nnn个数aia_iai​,aia_iai​表示以sis_isi​为中心的最长回文串串长. 再给你n−1n-1n−1个数bib_ ...

  8. windows 2008解决120天授权过期问题(亲测可用)

    https://blog.csdn.net/tladagio/article/details/80503198 最后的注册号码可以是:就是那个注册号码:5296992 4954438 6565792. ...

  9. abaqus的umat在vs中debug调试

    配置参考:https://www.jishulink.com/content/post/333909 常见错误:http://blog.sina.com.cn/s/blog_6116bc050100e ...

  10. Maven学习笔记2(坐标和依赖)

    1.坐标 Maven坐标为各个构件建立了秩序,任何一个构件都必须明确自己的坐标,一个maven坐标是由一些元素确定的 <groupId>com.alivn.account</grou ...