SpringBoot 2.x (10):整合Redis
Redis部署到阿里云:
下载redis源码,编译,允许远程访问的配置
阿里云安全组设置:
SSH连过去:
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
编译完成后cd到目录
vi redis.conf
bind改成0.0.0.0
protected-mode改成no
daemonize改为no(可选)
cd到src目录,运行redis:
./redis-server
也可以用守护进程的方式启动
设置密码:这一步是必须的,防止被人恶意连接
./redis-cli
config set requirepass [your password]
如果要关闭redis:
./redis-cli -p 6379 shutdown即可
测试是否远程连接成功的方式:采用RedisDesktopManager连接
SpringBoot整合Redis:
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
注意:SpringBoot默认操作Redis使用的是Lettuce而不是Jedis
网上大佬说Lettuce比Jedis性能好,我不了解,不做评论
如果想用Jedis,需要自行配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
下面是配置文件,其中Redis的配置是必须的,Redis Pool配置可选
Jedis配置文件:
# Redis
spring.redis.database=0
spring.redis.host=[Redis服务器IP]
spring.redis.port=6379
spring.redis.password=[密码]
spring.redis.timeout=3000
# Redis Pool
spring.redis.jedis.pool.max-idle=300
spring.redis.jedis.pool.min-idle=300
spring.redis.jedis.pool.max-active=2000
spring.redis.jedis.pool.max-wait=1000
Lettuce配置文件:我使用Lettuce的时候出现了各种BUG,简易还是用稳妥的Jedis吧
# Redis
spring.redis.database=0
spring.redis.host=[Redis服务器IP]
spring.redis.port=6379
spring.redis.password=[密码]
spring.redis.timeout=3000
# Redis Pool
spring.redis.lettuce.pool.max-idle=300
spring.redis.lettuce.pool.min-idle=300
spring.redis.lettuce.pool.max-active=2000
spring.redis.lettuce.pool.max-wait=1000
使用Spring的StringRedisTemplate进行简单的操作:
package org.dreamtech.redisdemo.controller; import java.util.HashMap;
import java.util.Map; 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.RestController; @RestController
public class RedisTestController { @Autowired
private StringRedisTemplate redisTpl; private Map<String, Object> modelMap = new HashMap<String, Object>(); @GetMapping("/add")
private Object add(String name) {
modelMap.clear();
if (name != null && !name.equals("")) {
redisTpl.opsForValue().set("name", name);
modelMap.put("success", true);
} else {
modelMap.put("success", false);
}
return modelMap;
} @GetMapping("/get")
private Object get() {
modelMap.clear();
String name = redisTpl.opsForValue().get("name");
modelMap.put("success", true);
modelMap.put("name", name);
return modelMap;
}
}
访问:
http://localhost:8080/add?name=xxx 设置name参数
http://localhost:8080/get 获取name参数
如果能够获取到设置的参数,说明整合redis成功
Redis工具类的简单封装:对其他数据类型可以自行进行封装,我这里只是最简单的操作封装
package org.dreamtech.redisdemo.util; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component; /**
* Redis工具类
*
* @author Xu Yiqing
*
*/
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate redisTpl; /**
* SET操作
*
* @param key KEY
* @param value VALUE
* @return 是否成功
*/
public boolean set(String key, String value) {
try {
redisTpl.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* GET操作
*
* @param key KEY
* @return VALUE
*/
public String get(String key) {
try {
String value = redisTpl.opsForValue().get(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
如何将对象存入Redis呢?
无法将对象存入Redis!但是可以把对象转为JSON存入Redis
实现:
JSON工具类封装:
package org.dreamtech.redisdemo.util; import java.io.IOException;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper; @SuppressWarnings("unchecked")
public class JsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); /**
* 对象转字符串
*
* @param <T> 泛型
* @param obj 对象
* @return 字符串
*/
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;
}
} /**
* 字符串转对象
*
* @param <T> 泛型
* @param str 字符串
* @param clazz 对象类型
* @return 对象
*/
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;
}
}
}
实体类:
package org.dreamtech.redisdemo.domain; public class User {
private String username;
private String password; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}
Controller:
package org.dreamtech.redisdemo.controller; import java.util.HashMap;
import java.util.Map; import org.dreamtech.redisdemo.domain.User;
import org.dreamtech.redisdemo.util.JsonUtils;
import org.dreamtech.redisdemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class RedisTestController { @Autowired
private RedisUtil redis; private Map<String, Object> modelMap = new HashMap<String, Object>(); @GetMapping("/add")
private Object add(String name) {
modelMap.clear();
boolean flag = redis.set("name", "redis");
if (flag) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
}
return modelMap;
} @GetMapping("/get")
private Object get() {
modelMap.clear();
String name = redis.get("name");
modelMap.put("success", true);
modelMap.put("name", name);
return modelMap;
} @GetMapping("/setuser")
private Object setUser() {
modelMap.clear();
User user = new User();
user.setUsername("admin");
user.setPassword("passsword");
boolean flag = redis.set("user", JsonUtils.obj2String(user));
if (flag) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
}
return modelMap;
} @GetMapping("/getuser")
private Object getUser() {
modelMap.clear();
String tempUser = redis.get("user");
User user = JsonUtils.string2Obj(tempUser, User.class);
modelMap.put("user", user);
modelMap.put("success", true);
return modelMap;
}
}
如果感觉Controller层测试太复杂,可以采用SpringBootTest:
package org.dreamtech.redisdemo; import org.dreamtech.redisdemo.domain.User;
import org.dreamtech.redisdemo.util.JsonUtils;
import org.dreamtech.redisdemo.util.RedisUtil;
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.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(classes = { RedisdemoApplication.class })
public class RedisTest { @Autowired
private RedisUtil redis; @Test
public void test() {
User tempUser = new User();
tempUser.setUsername("admin");
tempUser.setPassword("password");
String user = JsonUtils.obj2String(tempUser);
redis.set("user", user);
String result = redis.get("user");
System.out.println(result);
}
}
SpringBoot 2.x (10):整合Redis的更多相关文章
- 实例讲解Springboot以Template方式整合Redis及序列化问题
1 简介 之前讲过如何通过Docker安装Redis,也讲了Springboot以Repository方式整合Redis,建议阅读后再看本文效果更佳: (1) Docker安装Redis并介绍漂亮的可 ...
- springboot学习笔记-3 整合redis&mongodb
一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable ...
- SpringBoot学习- 5、整合Redis
SpringBoot学习足迹 SpringBoot项目中访问Redis主要有两种方式:JedisPool和RedisTemplate,本文使用JedisPool 1.pom.xml添加dependen ...
- 【SpringBoot】Springboot2.x整合Redis(一)
备注: springboto整合redis依赖于spring-boot-starter-data-redis这个jar 一,项目环境和依赖 1.POM.xml配置 <parent> < ...
- springboot笔记10——整合Redis
依赖 <dependencies> <!--web依赖--> <dependency> <groupId>org.springframework.boo ...
- SpringBoot使用注解方式整合Redis
1.首先导入使用Maven导入jar包 <dependency> <groupId>org.springframework.boot</groupId> <a ...
- 实例讲解Springboot以Repository方式整合Redis
1 简介 Redis是高性能的NoSQL数据库,经常作为缓存流行于各大互联网架构中.本文将介绍如何在Springboot中整合Spring Data Redis,使用Repository的方式操作. ...
- SpringBoot(三)整合Redis
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
- SpringBoot进阶教程(二十六)整合Redis之共享Session
集群现在越来越常见,当我们项目搭建了集群,就会产生session共享问题.因为session是保存在服务器上面的.那么解决这一问题,大致有三个方案,1.通过nginx的负载均衡其中一种ip绑定来实现( ...
- SpringBoot进阶教程(二十九)整合Redis 发布订阅
SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 实现了 发布/订阅消息范例,发送者 (publishers) 不用编程就可以向特定的接受者发送消息 (subscribers). Ra ...
随机推荐
- codevs 1497取余运算
1497 取余运算 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamon 题目描述 Description 输入b,p,k的值,编程计算bp mod k的值. ...
- bzoj 3745 [Coci2015]Norma——序列分治
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3745 如果分治,就能在本层仅算过 mid 的区间了. 可以从中间到左边地遍历左边,给右边两个 ...
- android性能测试工具
Android性能测试工具Emmagee介绍 Emmagee介绍 Emmagee是监控指定被测应用在使用过程中占用机器的CPU.内存.流量资源的性能测试小工具.该工具的优势在于如同windows系 ...
- CF-807B
B. T-Shirt Hunt time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...
- ORA-22992:没法使用从远程表选择的LOB定位器
OLB 问题 ORA-22992:没法使用从远程表选择的LOB定位器 Create global temporary table temp on commit preserve rows as sel ...
- console.log是异步么?
让我们来看一个例子: var a = {}; console.log(a); a.foo = 'foo'; 4 console.log(a); 但是问题来了:在chorme跟firfox一样么? 结果 ...
- RXJS组件间超越父子关系的相互通信
RXJS组件间超越父子关系的相互通信 用到这个的需求是这样的: 组件A有数据变化,将变化的数据流通知组件B接收这个数据流并做相应的变化 实例化RXJS的subject对象 import { Injec ...
- HDU - 1019 - Least Common Multiple - 质因数分解
http://acm.hdu.edu.cn/showproblem.php?pid=1019 LCM即各数各质因数的最大值,搞个map乱弄一下就可以了. #include<bits/stdc++ ...
- 347. Top K Frequent Elements (sort map)
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- CodeForces 761C 【DP】
总结:能这么DP就这么写! 多练位运算标记. #include<bits/stdc++.h> using namespace::std; const int N=55; const int ...