========================9、SpringBoot2.x整合Redis实战 ================================

1、分布式缓存Redis介绍
简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具

通过缓存减少数据库访问,提高访问速度

1、redis官网 https://redis.io/download

2、新手入门redis在线测试工具:http://try.redis.io/

2、源码编译安装Redis4.x
简介:使用源码安装Redis4.x和配置外网访问

1、快速安装 https://redis.io/download#installation
wget http://download.redis.io/releases/redis-4.0.9.tar.gz
tar xzf redis-4.0.9.tar.gz
cd redis-4.0.9
make

启动服务端:src/redis-server
启动客户端:src/redis-cli

2、默认是本地访问的,需要开放外网访问
1)打开redis.conf文件在NETWORK部分修改
注释掉bind 127.0.0.1可以使所有的ip访问redis
修改 protected-mode,值改为no

查看当前占用端口

3、SpringBoot2.x整合redis实战讲解

简介:使用springboot-starter整合reids实战

1、官网:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-redis
集群文档:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#cluster

2、springboot整合redis相关依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

3、相关配置文件配置
#=========redis基础配置=========
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6390
# 连接超时时间 单位 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

4、常见redistemplate种类讲解和缓存实操(使用自动注入)

1、注入模板
@Autowired
private StirngRedisTemplate strTplRedis

2、类型String,List,Hash,Set,ZSet
对应的方法分别是opsForValue()、opsForList()、opsForHash()、opsForSet()、opsForZSet()

package com.atguigu.springboot.controller;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.atguigu.springboot.controller.domain.JsonData; @RestController
@RequestMapping("/api/v1/redis")
public class RdisTestController { @Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate @GetMapping(value="add")
public Object add(){ //opsForValue : Returns the operations performed on simple values (or Strings in Redis terminology). redisTpl.opsForValue().set("name", "xdclass2018"); return JsonData.buildSuccess(); } @GetMapping(value="get")
public Object get(){ String value = redisTpl.opsForValue().get("name");
return JsonData.buildSuccess(value); } }

controller

4、Redis工具类封装讲解和实战
简介:高效开发方式 Redis工具类封装讲解和实战
1、常用客户端 https://redisdesktop.com/download
2、封装redis工具类并操作

utils用于 对象 转str    str转对象

package net.xdclass.base_project.utils;

import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

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;
}
}
}

utils

package net.xdclass.base_project.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component; /**
* 功能描述:redis工具类
*
* <p> 创建时间:Apr 29, 2018 10:07:30 PM </p>
*
*@作者 小D课堂 小D
*/
@Component
public class RedisClient { @Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate /**
* 功能描述:设置key-value到redis中
* @param key
* @param value
* @return
*/
public boolean set(String key ,String value){
try{
redisTpl.opsForValue().set(key, value);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
} } /**
* 功能描述:通过key获取缓存里面的值
* @param key
* @return
*/
public String get(String key){
return redisTpl.opsForValue().get(key);
} // @Autowired
// private StringRedisTemplate redisTemplate;
//
//
// /**
// * 通过字符串key获取值
// * @param key 键
// * @return 值
// */
// public String get(String key){
// return key==null?null:redisTemplate.opsForValue().get(key);
// }
//
//
// /**
// * 普通缓存放入
// * @param key 键
// * @param value 值
// * @return true成功 false失败
// */
// public boolean set(String key,String value) {
// try {
// redisTemplate.opsForValue().set(key, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
//
// }
// //
// /**
// * 功能描述:设置某个key过期时间
// * @param key
// * @param time
// * @return
// */
// public boolean expire(String key,long time){
// try {
// if(time>0){
// redisTemplate.expire(key, time, TimeUnit.SECONDS);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
//
//
//
// /**
// * 功能描述:根据key 获取过期时间
// * @param key
// * @return
// */
// public long getExpire(String key){
// return redisTemplate.getExpire(key,TimeUnit.SECONDS);
// }
//
//
// /**
// * 递增
// * @param key 键
// * @return
// */
// public long incr(String key, long delta){
// return redisTemplate.opsForValue().increment(key, delta);
// }
//
//
// /**
// * 递减
// * @param key 键
// * @param delta 要减少几
// * @return
// */
// public long decr(String key, long delta){
// return redisTemplate.opsForValue().increment(key, -delta);
// }
//
// //==============Map结构=====================
//
//
// //==============List结构=====================
//
//
// }

client

package net.xdclass.base_project.controller;

import java.util.Date;

import net.xdclass.base_project.domain.JsonData;
import net.xdclass.base_project.domain.User;
import net.xdclass.base_project.utils.JsonUtils;
import net.xdclass.base_project.utils.RedisClient; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/api/v1/redis")
public class RdisTestController { @Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate @Autowired
private RedisClient redis; @GetMapping(value="add")
public Object add(){ //redisTpl.opsForValue().set("name", "xdclass2018");
redis.set("username", "xddddddd");
return JsonData.buildSuccess(); } @GetMapping(value="get")
public Object get(){ //String value = redisTpl.opsForValue().get("name");
String value = redis.get("username");
return JsonData.buildSuccess(value); } @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); } @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); } }

controller

test单元测试

package base_project.base;

import net.xdclass.base_project.XdclassApplication;
import net.xdclass.base_project.domain.User;
import net.xdclass.base_project.utils.JsonUtils;
import net.xdclass.base_project.utils.RedisClient; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程
public class JsonTest { @Autowired
private StringRedisTemplate strTpl; @Autowired
private RedisClient redis; @Test
public void testOne(){
User u = new User();
u.setAge(1);
u.setPhone("22222");
u.setPwd("0000"); String str = JsonUtils.obj2String(u);
strTpl.opsForValue().set("str", str);
System.out.println(str); } }

test

【SpringBoot】整合Redis实战的更多相关文章

  1. SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码

    创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...

  2. SpringBoot2.x整合Redis实战 4节课

    1.分布式缓存Redis介绍      简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/download          2.新手 ...

  3. springboot整合redis——redisTemplate的使用

    一.概述 相关redis的概述,参见Nosql章节 redisTemplate的介绍,参考:http://blog.csdn.net/ruby_one/article/details/79141940 ...

  4. 小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_39、SpringBoot2.x整合redis实战讲解

    笔记 3.SpringBoot2.x整合redis实战讲解 简介:使用springboot-starter整合reids实战 1.官网:https://docs.spring.io/spring-bo ...

  5. SpringBoot整合Redis、ApachSolr和SpringSession

    SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...

  6. SpringBoot整合Redis及Redis工具类撰写

            SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...

  7. SpringBoot 整合 Redis缓存

    在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. Spr ...

  8. SpringBoot系列十:SpringBoot整合Redis

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Redis 2.背景 Redis 的数据库的整合在 java 里面提供的官方工具包:jed ...

  9. springboot整合redis(注解形式)

    springboot整合redis(注解形式) 准备工作 springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring ...

随机推荐

  1. 【三】jquery之选择器

    转自:https://www.cnblogs.com/youfeng365/p/5846650.html jquery参考手册:http://jquery.cuishifeng.cn/index.ht ...

  2. Java原生API访问MongoDB

    1.pom.xml <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java ...

  3. 【文献07】基于MPC的WMR点镇定-极坐标系下和轨迹跟踪

    参考: Kuhne F , Lages W , Silva J D . Point stabilization of mobile robots with nonlinear model predic ...

  4. CentOS安装vmtools后 共享文件不能显示的问题

    摘要:以 下这些方法都是我转自网上的一些比较靠谱的方法,但是大多都是针对ununtu的,特别是针对共享文件挂载的相应处理方法.所以在这里,我主要是这对 centos不能显示共享文件的问题做了重点的介绍 ...

  5. RDP服务开启

    一.RDP协议概述 远程桌面协议(RDP, Remote Desktop Protocol)是一个多通道(multi-channel)的协议,让用户(客户端或称“本地电脑”)连上提供微软终端机服务的电 ...

  6. Django框架(六)

    十一.Django组件-cookie与session 1.会话跟踪技术 (1) 什么是会话跟踪技术 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多 ...

  7. SQL Server-执行计划教会我如何创建索引

    先说点废话 以前有 DBA 在身边的时候,从来不曾考虑过数据库性能的问题,但是,当一个应用程序从头到脚都由自己完成,而且数据库面对的是接近百万的数据,看着一个页面加载速度像乌龟一样,自己心里真是有种挫 ...

  8. 学生信息管理系统(C语言)

    #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct student ...

  9. 数据的双向绑定 Angular JS之开端篇

    接触AngularJS许了,时常问自己一些问题,如果是我实现它,会在哪些方面选择跟它相同的道路,哪些方面不同.为此,记录了一些思考,给自己回顾,也供他人参考. 初步大致有以下几个方面: 数据双向绑定 ...

  10. wishhack 玩法概览

    抢流量玩法 超级店长玩法 https://www.wishhack.com/article/50.html https://www.wishhack.com/article/43.html