Redis:Spring框架下Redis的配置和调用,xml文件中redis的配置,redisTemplate的使用和jedis的使用
老规矩了,再次重复一遍,配置XML文件为Spring框架所属,所使用的框架是Spring,非SpringBoot!!!
Spring框架整合Redis并且使用
1.配置文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true" /><property name="order" value="1" /> <property name="locations"> <list> <value>classpath:jdbc.properties</value><value>classpath:application.properties</value><value>classpath:config.properties</value> 这里是读取redis信息的位置</list> </property> </bean><!-- redis config start --><!-- 配置JedisPoolConfig实例 --><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxIdle" value="${redis.maxIdle}" /><property name="maxTotal" value="${redis.maxActive}" /><property name="maxWaitMillis" value="${redis.maxWait}" /><property name="testOnBorrow" value="${redis.testOnBorrow}" /></bean><!-- 配置JedisConnectionFactory --><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><property name="hostName" value="${redis.host}"/><property name="port" value="${redis.port}"/><property name="password" value="${redis.pass}"/><property name="database" value="${redis.dbIndex}"/><property name="poolConfig" ref="poolConfig"/></bean><!-- 配置RedisTemplate --><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"><property name="connectionFactory" ref="jedisConnectionFactory"/></bean><!-- 配置RedisCacheManager --><bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"><constructor-arg name="redisOperations" ref="redisTemplate" /><property name="defaultExpiration" value="${redis.expiration}"/></bean><!-- 配置RedisCacheConfig --><bean id="redisCacheConfig" class="com.yhl.aps.common.redis.RedisCacheConfig"><constructor-arg ref="jedisConnectionFactory" /><constructor-arg ref="redisTemplate" /><constructor-arg ref="redisCacheManager" /></bean><!-- redis config end -->
配上配置文件的内容
我这么写是为了区分不同环境下的 不同ip 和端口
如果 你不用区分,将下列代码片段,直接放在 config里就可以
#redis配置
redis.host=10.7.60.151
redis.port=6379
redis.pass=123456
#redis的可连接数据库数量默认0 最大16 数量是0-15(database-1)
redis.dbIndex=0
redis.expiration=3000
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
管理redis的缓存配置类
package com.yhl.aps.common.redis;import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;import java.lang.reflect.Method;/*** 以Spring与配置文件来管理的redis缓存配置类* @author zhangjian**/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {private volatile JedisConnectionFactory mJedisConnectionFactory;private volatile RedisTemplate<String, String> mRedisTemplate;private volatile RedisCacheManager mRedisCacheManager;public RedisCacheConfig() {super();}public RedisCacheConfig(JedisConnectionFactory mJedisConnectionFactory, RedisTemplate<String,String> mRedisTemplate,RedisCacheManager mRedisCacheManager) {super();this.mJedisConnectionFactory = mJedisConnectionFactory;this.mRedisTemplate = mRedisTemplate;this.mRedisCacheManager = mRedisCacheManager;}public JedisConnectionFactory redisConnectionFactory() {return mJedisConnectionFactory;}public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {return mRedisTemplate;}public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {return mRedisCacheManager;}@Beanpublic KeyGenerator customKeyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object o, Method method, Object... objects) {StringBuilder sb = new StringBuilder();sb.append(o.getClass().getName());sb.append(method.getName());for (Object obj : objects) {sb.append(obj.toString());}return sb.toString();}};}
}
重点!!! 那到底在代码中怎么调用呢
在你需要使用的地方直接注入
@Resource
private RedisTemplate<String, Object> redisTemplate;
然后直接调用就可以
set方法 就是 redisTemplate.opsForValue().set(key, value);
get方法就是redisTemplate.opsForValue().get(key)
然后我列举一些在下面这个工具类里,自行取走
package com.yhl.aps.common.redis;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** @ClassName: RedisUtil* @Package: com.yhl.aps.common.redis* @Description: 描述* @Author: zhangjian* @Date: 2021-01-07 00:19* @Copyright: 悠桦林信息科技(上海)有限公司*/
@Component
public final class RedisUtil {private Logger log = LoggerFactory.getLogger(RedisUtil.class);@Resourceprivate RedisTemplate<String, Object> redisTemplate;public Set<String> keys(String keys) {try {return redisTemplate.keys(keys);} catch (Exception e) {log.error("", e);return null;}}/*** 指定缓存失效时间** @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) {log.error("", e);return false;}}/*** 根据key 获取过期时间** @param key* 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/*** 判断key是否存在** @param key* 键* @return true 存在 false不存在*/public boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {log.error("", e);return false;}}/*** 删除缓存** @param key* 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(CollectionUtils.arrayToList(key));}}}/*** 普通缓存获取** @param key* 键* @return 值*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 普通缓存放入** @param key* 键* @param value* 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 普通缓存放入并设置时间** @param key* 键* @param value* 值* @param time* 时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {log.error("", e);return false;}}/*** 递增** @param key* 键* @param delta* 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减** @param key* 键* @param delta* 要减少几(小于0)* @return*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}/*** HashGet** @param key* 键 不能为null* @param item* 项 不能为null* @return 值*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 获取hashKey对应的所有键值** @param key* 键* @return 对应的多个键值*/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/*** HashSet** @param key* 键* @param map* 对应多个键值* @return true 成功 false 失败*/public boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {log.error("", e);return false;}}/*** HashSet 并设置时间** @param key* 键* @param map* 对应多个键值* @param time* 时间(秒)* @return true成功 false失败*/public boolean hmset(String key, Map<String, Object> map, long time) {try {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {log.error("", e);return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key* 键* @param item* 项* @param value* 值* @return true 成功 false失败*/public boolean hset(String key, String item, Object value) {try {redisTemplate.opsForHash().put(key, item, value);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key* 键* @param item* 项* @param value* 值* @param time* 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间* @return true 成功 false失败*/public boolean hset(String key, String item, Object value, long time) {try {redisTemplate.opsForHash().put(key, item, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {log.error("", e);return false;}}/*** 删除hash表中的值** @param key* 键 不能为null* @param item* 项 可以使多个 不能为null*/public void hdel(String key, Object... item) {redisTemplate.opsForHash().delete(key, item);}/*** 判断hash表中是否有该项的值** @param key* 键 不能为null* @param item* 项 不能为null* @return true 存在 false不存在*/public boolean hHasKey(String key, String item) {return redisTemplate.opsForHash().hasKey(key, item);}/*** hash递增 如果不存在,就会创建一个 并把新增后的值返回** @param key* 键* @param item* 项* @param by* 要增加几(大于0)* @return*/public double hincr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, by);}/*** hash递减** @param key* 键* @param item* 项* @param by* 要减少记(小于0)* @return*/public double hdecr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, -by);}/*** 根据key获取Set中的所有值** @param key* 键* @return*/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {log.error("", e);return null;}}/*** 根据value从一个set中查询,是否存在** @param key* 键* @param value* 值* @return true 存在 false不存在*/public boolean sHasKey(String key, Object value) {try {return redisTemplate.opsForSet().isMember(key, value);} catch (Exception e) {log.error("", e);return false;}}/*** 将数据放入set缓存** @param key* 键* @param values* 值 可以是多个* @return 成功个数*/public long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {log.error("", e);return 0;}}/*** 将set数据放入缓存** @param key* 键* @param time* 时间(秒)* @param values* 值 可以是多个* @return 成功个数*/public long sSetAndTime(String key, long time, Object... values) {try {Long count = redisTemplate.opsForSet().add(key, values);if (time > 0)expire(key, time);return count;} catch (Exception e) {log.error("", e);return 0;}}/*** 获取set缓存的长度** @param key* 键* @return*/public long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {log.error("", e);return 0;}}/*** 移除值为value的** @param key* 键* @param values* 值 可以是多个* @return 移除的个数*/public long setRemove(String key, Object... values) {try {Long count = redisTemplate.opsForSet().remove(key, values);return count;} catch (Exception e) {log.error("", e);return 0;}}/*** 获取list所有值** @param key* 键* @return*/public List<Object> lGet(String key) {try {return redisTemplate.opsForList().range(key, 0, -1);} catch (Exception e) {log.error("", e);return null;}}/*** 获取list缓存部分内容** @param key* 键* @param start* 开始* @param end* 结束 0 到 -1代表所有值* @return*/public List<Object> lGet(String key, long start, long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {log.error("", e);return null;}}/*** 获取list缓存的长度** @param key* 键* @return*/public long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {log.error("", e);return 0;}}/*** 通过索引 获取list中的值** @param key* 键* @param index* 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推* @return*/public Object lGetIndex(String key, long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {log.error("", e);return null;}}/*** 将值放入缓存中的list** @param key* 键* @param value* 值* @return*/public boolean lSet(String key, Object value) {try {redisTemplate.opsForList().rightPush(key, value);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 将list放入缓存** @param key* 键* @param value* 值* @param time* 时间(秒)* @return*/public boolean lSet(String key, Object value, long time) {try {redisTemplate.opsForList().rightPush(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 将list放入缓存** @param key* 键* @param value* 值* @return*/public boolean lSet(String key, List<Object> value) {try {redisTemplate.opsForList().rightPushAll(key, value);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 将list放入缓存** @param key* 键* @param value* 值* @param time* 时间(秒)* @return*/public boolean lSet(String key, List<Object> value, long time) {try {redisTemplate.opsForList().rightPushAll(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 根据索引修改list中的某条数据** @param key* 键* @param index* 索引* @param value* 值* @return*/public boolean lUpdateIndex(String key, long index, Object value) {try {redisTemplate.opsForList().set(key, index, value);return true;} catch (Exception e) {log.error("", e);return false;}}/*** 移除N个值为value** @param key* 键* @param count* 移除多少个* @param value* 值* @return 移除的个数*/public long lRemove(String key, long count, Object value) {try {Long remove = redisTemplate.opsForList().remove(key, count, value);return remove;} catch (Exception e) {log.error("", e);return 0;}}
}
上述工具类,来自于别的博主,不过我已经找不到博主的信息了,就不备注了。
下面在提供一个 Jedis的调用案例,非常简单,
Jedis jedis=new Jedis("127.0.0.1",6379);//ip 和端口jedis.auth("password");//密码jedis.set("key","value");jedis.get("key");
Redis:Spring框架下Redis的配置和调用,xml文件中redis的配置,redisTemplate的使用和jedis的使用相关推荐
- SSM框架下后台数据库传送到前端jsp文件中
SSM框架中后台存储在数据库中的数据,如何传送到前端中使用呢? 前提:SSM框架已经搭好: Category.xml中的SQL语句集已经写好 Category中的GetXX()和SetXX()方法也已 ...
- java 自动装载_java_详解Java的Spring框架下bean的自动装载方式,Spring容器可以自动装配相互协 - phpStudy...
详解Java的Spring框架下bean的自动装载方式 Spring容器可以自动装配相互协作bean之间的关系,这有助于减少对XML配置,而无需编写一个大的基于Spring应用程序的较多的和元素. 自 ...
- java面试(二十五)--(1)redis为什么读写速率快性能好(2)说说web.xml文件中可以配置哪些内容(3)和的区别(4)扑克牌顺子
1. redis为什么读写速率快性能好? 1.Redis将数据存储在内存上,避免了频繁的IO操作 2.Redis其本身采用字典的数据结构,时间复杂度为O(1),且其采用渐进式的扩容手段 3.Redis ...
- 深入剖析 RabbitMQ —— Spring 框架下实现 AMQP 高级消息队列协议
前言 消息队列在现今数据量超大,并发量超高的系统中是十分常用的.本文将会对现时最常用到的几款消息队列框架 ActiveMQ.RabbitMQ.Kafka 进行分析对比. 详细介绍 RabbitMQ 在 ...
- 解决Spring框架下中文乱码的问题
解决Spring框架下中文乱码的问题 参考文章: (1)解决Spring框架下中文乱码的问题 (2)https://www.cnblogs.com/Summer7C/p/4712818.html (3 ...
- Spring框架学习day_03:对于读取文件方式的补充/关于spring框架知识点的学习方式
1. 通过Environment读取.properties配置文件 假设在src/main/resources下存在jdbc.properties文件,并且,在该文件中存在若干条配置信息,如果需要读取 ...
- Spring 在xml文件中配置Bean
Spring容器是一个大工厂,负责创建.管理所有的Bean. Spring容器支持2种格式的配置文件:xml文件.properties文件,最常用的是xml文件. Bean在xml文件中的配置 < ...
- 【MyBatis学习05】SqlMapConfig.xml文件中的配置总结
经过上两篇博文的总结,对mybatis中的dao开发方法和流程基本掌握了,这一节主要来总结一下mybatis中的全局配置文件SqlMapConfig.xml在开发中的一些常用配置,首先看一下该全局配置 ...
- web.xml文件中可以配置哪些内容?
web.xml用于配置Web应用的相关信息,如:监听器(listener).过滤器(filter).Servlet.相关参数. 会话超时时间.错误页面等①配置Spring上下文加载监听器,加载Spri ...
最新文章
- linux测试网页装载时间,使用curl测试web页面响应加载速度
- (42) Aeroo 模板实战
- 一个支持 CodeFirst/DbFirst/ModelFirst 的数据库小工具
- iOS linker command failed with exit code 1 (use -v to see invocation)多种解决方案汇总
- django-模型类的查询方法
- 联调测试是什么意思_功能模块提测前注意这几件事,再也不怕被测试diss了
- 安卓自定义view全解:初始化,onDraw函数,onMeasure函数,用户手势事件
- 国外手机短信验证码接收神器(转自美国华人网FuninUSA)
- CABAC 基础二-算术编码
- python模拟火车订票系统_毕业论文:火车票网上订票系统
- C# TCP通讯大族激光打标机
- 难崩日记——从入门到入土的求生之路(二):文件上传中的路径问题
- 猫眼电影爬虫(参考崔大的书写的)
- Vuforia⭐️Unity实现对手机陀螺仪的调用
- Use After Free
- 毕设-基于LoRa的智能农业大棚
- 微信公众号二次开发关键字回复图文
- 第三篇 颜色的合成与计算
- miui 8 android对应关系,MIUI2.3到MIUI8的演变过程,满满的回忆
- echarts象形图pictorialBar
热门文章
- 最简单的基于FFMPEG的封装格式转换器(C++Qt 版)
- matlab车牌识别代码项目
- python初体验-hello world答案_Python基础学习之Python初体验
- 内存带宽意味着什么?
- 原创 - 如何观察我们的大脑?脑成像技术简介
- python调用百度地图画轨迹图_百度地图 API 绘制路线
- Android Chromium WebView学习
- win7要用到很多运行命令
- Spring中的IoC(控制反转)和DI(依赖注入)
- .Net + ABP + vue-element-admin Caviar快速开发框架