Java项目集成Redis
1.项目pom.xml中添加Jedis依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.项目application.properties中添加Redis配置信息
# Redis 相关配置
redis.host=127.0.0.1
redis.port=6379
redis.password=112233
redis.timeout=300
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3
3.com.xxx.redis包:
①RedisConfig类:读取配置文件中的Redis配置信息
@Component
@ConfigurationProperties(prefix="redis")
public class RedisConfig { private String host;
private int port;
//秒
private int timeout;
private String password;
private int poolMaxTotal;
private int poolMaxIdle;
//秒
private int poolMaxWait; public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public int getTimeout() {
return timeout;
} public void setTimeout(int timeout) {
this.timeout = timeout;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public int getPoolMaxTotal() {
return poolMaxTotal;
} public void setPoolMaxTotal(int poolMaxTotal) {
this.poolMaxTotal = poolMaxTotal;
} public int getPoolMaxIdle() {
return poolMaxIdle;
} public void setPoolMaxIdle(int poolMaxIdle) {
this.poolMaxIdle = poolMaxIdle;
} public int getPoolMaxWait() {
return poolMaxWait;
} public void setPoolMaxWait(int poolMaxWait) {
this.poolMaxWait = poolMaxWait;
}
}
②RedisPoolFactory类:通过JedisPool的构造方法及配置参数,获取JedisPool
@Service
public class RedisPoolFactory { @Autowired
private RedisConfig redisConfig; /**
* 获得的JedisPool注入Spring的容器中
* @return
*/
@Bean
public JedisPool jedisPoolFactory() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000); JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisConfig.getHost(),
redisConfig.getPort(), redisConfig.getTimeout(), redisConfig.getPassword(), 0); return jedisPool;
}
③KeyPrefix类:定义各个对象存储在Redis中的key的前缀
public interface KeyPrefix {
public int expireSeconds();
public String getPrefix();
}
public abstract class BasePrefix implements KeyPrefix{
private int expireSeconds;
private String prefix;
//0代表永不过期
public BasePrefix(String prefix) {
this(0,prefix);
}
public BasePrefix(int expireSeconds, String prefix) {
this.expireSeconds = expireSeconds;
this.prefix = prefix;
}
@Override
public int expireSeconds(){
return expireSeconds;
}
@Override
public String getPrefix(){
String className = getClass().getSimpleName();
return className+":" + prefix;
}
}
public class UserKey extends BasePrefix{
/**
* 父类构造方法
* @param prefix
*/
private UserKey(String prefix) {
super(prefix);
}
private UserKey(int expireSeconds, String prefix) {
super(expireSeconds, prefix);
}
public static UserKey getById = new UserKey(30, "id");
public static UserKey getByName = new UserKey(30, "name");
}
④RedisService类:通过JedisPool获取Jedis;通过Jedis客户端处理缓存数据
@Service
public class RedisService { @Autowired
private RedisPoolFactory redisPoolFactory; /**
* 获取对象
* @param key
* @param clazz
* @param <T>
* @return
*/
public <T> T getRedis(KeyPrefix prefix,String key, Class<T> clazz) { JedisPool jedisPool = redisPoolFactory.jedisPoolFactory();
Jedis jedis = null;
try{
jedis = jedisPool.getResource(); String realKey = prefix.getPrefix() + key;
String value = jedis.get(realKey);
T realValue = stringToBean(value,clazz);
return realValue;
}finally{
returnToPool(jedis);
} } public <T> boolean setRedis(KeyPrefix prefix,String key, T value) { JedisPool jedisPool = redisPoolFactory.jedisPoolFactory();
Jedis jedis = null;
try{
jedis = jedisPool.getResource(); String valueStr = beanToString(value); String realKey = prefix.getPrefix() + key; if(valueStr == null || valueStr.length() <= 0) {
return false;
}
jedis.set(realKey, valueStr); return true;
}finally{
returnToPool(jedis);
} } /**
* 删除
* */
public boolean delete(KeyPrefix prefix, String key) {
JedisPool jedisPool = redisPoolFactory.jedisPoolFactory();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
long ret = jedis.del(realKey);
return ret > 0;
}finally {
returnToPool(jedis);
}
} /**
* 增加值
* */
public <T> Long incr(KeyPrefix prefix, String key) {
JedisPool jedisPool = redisPoolFactory.jedisPoolFactory();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.incr(realKey);
}finally {
returnToPool(jedis);
}
} private void returnToPool(Jedis jedis){
if(null != jedis){
jedis.close();
}
} public static <T> String beanToString(T value) {
if(value == null) {
return null;
}
Class<?> clazz = value.getClass();
if(clazz == int.class || clazz == Integer.class) {
return ""+value;
}else if(clazz == String.class) {
return (String)value;
}else if(clazz == long.class || clazz == Long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
} @SuppressWarnings("unchecked")
public static <T> T stringToBean(String str, Class<T> clazz) {
if(str == null || str.length() <= 0 || clazz == null) {
return null;
}
if(clazz == int.class || clazz == Integer.class) {
return (T)Integer.valueOf(str);
}else if(clazz == String.class) {
return (T)str;
}else if(clazz == long.class || clazz == Long.class) {
return (T)Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
}
}
4. 控制层:连接Redis服务器,测试
1 /**
* 获取用户
* 测试Redis服务
* @return
*/
@RequestMapping("/testRedisGet")
@ResponseBody
public Result<User> testRedis(@RequestParam("id") int id){ User user = redisService.getRedis(UserKey.getById,id + "", User.class); return Result.success(user);
} //写入Redis
@RequestMapping("/testRedisSet")
@ResponseBody
public Result<User> testRedisSet(@RequestParam("id") int id,
@RequestParam("name") String name){ User user = new User();
user.setId(id);
user.setName(name);
redisService.setRedis(UserKey.getById,id + "", user); return Result.success(user);
}
Java项目集成Redis的更多相关文章
- Spring Boot 项目集成Redis
目录 集成方式 使用Jedis 使用spring-data-redis Redis的安装 绑定配置 获取Redis客户端 Redis工具的编写 使用 集成方式 使用Jedis Jedis是Redis官 ...
- Java项目配置redis
成功配置redis之后,便来学习使用redis.首先了解下redis的数据类型. Redis的数据类型 Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set( ...
- SpringBoot项目集成Redis
一.在pom文件中添加依赖 <!-- 集成redis --> <dependency> <groupId>org.springframework.boot</ ...
- 谷粒 | 项目集成redis
添加依赖 由于redis缓存是公共应用,所以我们把依赖与配置添加到了common模块下面,在common模块pom.xml下添加以下依赖 <!-- redis --> <depend ...
- Java项目集成SAP BO
SAP BO报表查看需要登录SAP BO系统,为了方便公司希望将BO报表集成到OA系统中,所以参考网上资料加上与SAP BO的顾问咨询整理出一套通过Java来集成SAP BO的功能. SAPBO中的报 ...
- Taurus.MVC 微服务框架 入门开发教程:项目集成:3、客户端:其它编程语言项目集成:Java集成应用中心。
系列目录: 本系列分为项目集成.项目部署.架构演进三个方向,后续会根据情况调整文章目录. 开源地址:https://github.com/cyq1162/Taurus.MVC 本系列第一篇:Tauru ...
- Spring Boot集成Redis集群(Cluster模式)
目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...
- Spring Boot 项目实战(四)集成 Redis
一.前言 上篇介绍了接口文档工具 Swagger 及项目监控工具 JavaMelody 的集成过程,使项目更加健壮.在 JAVA Web 项目某些场景中,我们需要用缓存解决如热点数据访问的性能问题,业 ...
- redis在java项目中的使用
在上一篇文章中已经讲了redis的spring配置,这篇将会描述redis在java项目中的使用. redis存储形式都是key-value(键值对),按照存储的内容分为两种,一种是存简单数据,即数字 ...
随机推荐
- docker 学习之路 将docker容器变为镜像并上传
环境 ubunt 16.4 去hub.docker.com上注册一个账号,并在账号中注册一个公有public或者私有仓库private 步骤如下 如上图 点击该处进入创建docker库页面 除了名字之 ...
- <字符串匹配>KMP算法为何比暴力求解的时间复杂度更低?
str表示文本串,m表示模式串; str[i+j] 和 m[j] 是正在进行匹配的字符; KMP的时间复杂度是O(m+n) , 暴力求解的时间复杂度是O(m*n) KMP利用了B[0:j]和A[i ...
- Tries前缀树
Trie,来源于(retrieval,取回,数据检索),是一种多叉树,用来存储字母表上的单词非常有用. Trie经常用来存储动态集合(dynamic set)或者关联数组(associative ar ...
- Js中的window.parent ,window.top,window.self 了解
在应用有frameset或者iframe的页面时,parent是父窗口,top是最顶级父窗口(有的窗口中套了好几层frameset或者iframe),self是当前窗口, opener是用open方法 ...
- ret.data[0]._highlight = true iview table表格高亮
ret.data[0]._highlight = true iview table表格高亮
- Java8 Stream流
第三章 Stream流 <Java8 Stream编码实战>的代码全部在https://github.com/yu-linfeng/BlogRepositories/tree/master ...
- 使用tomcat运行时提示some characters cannot be mapped using iso-8859-1 character encoding异常
今天第一次使用java进行jsp项目搭建,也是第一次使用tomcat.tomcat是运行java web的一个小型服务器,属于Apache的一个开源免费的服务. 在运行web 的时候,我们就要先配置好 ...
- Ubuntu16.04安装QQ机器人
Ubuntu安装QQ机器人 看了看现在QQ机器人似乎只有酷Q机器人有Docker可以在linux上运行了 那就k开始装酷Q机器人,资源占用也不是很大,大概占用180M内存吧 安装酷Q HTTP 首先安 ...
- hdu2612 又是迷宫系列
题目链接:http://icpc.njust.edu.cn/Problem/Hdu/2612/ 题意:有两个人在地图上不同的位置,地图上由若干个餐厅,求两人能同时到达一个餐厅所用最少的总时间. 代码如 ...
- [二分,multiset] 2019 Multi-University Training Contest 10 Welcome Party
Welcome Party Time Limit: 4000/4000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)T ...