SpringBoot 2.x (10):整合Redis
2019-05-10 06:07:21来源:博客园 阅读 ()
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); } }
原文链接:https://www.cnblogs.com/xuyiqing/p/10838071.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:java之正则表达式
- springboot2配置JavaMelody与springMVC配置JavaMelody 2020-06-11
- SpringBoot 2.3 整合最新版 ShardingJdbc + Druid + MyBatis 2020-06-11
- 掌握SpringBoot-2.3的容器探针:实战篇 2020-06-11
- nacos~配置中心功能~springboot的支持 2020-06-10
- SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后 2020-06-10
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash