04.spring-data-redis与Jedis整合使用
1.spring-data-redis与Jedis简单整合
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd"default-lazy-init="false"><!-- 连接池配置. --><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"><!-- 连接池中最大连接数。高版本:maxTotal,低版本:maxActive --><property name="maxTotal" value="8" /><!-- 连接池中最大空闲的连接数. --><property name="maxIdle" value="4" /><!-- 连接池中最少空闲的连接数. --><property name="minIdle" value="1" /><!-- 当连接池资源耗尽时,调用者最大阻塞的时间,超时将跑出异常。单位,毫秒数;默认为-1.表示永不超时。高版本:maxWaitMillis,低版本:maxWait --><property name="maxWaitMillis" value="5000" /><!-- 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除. --><property name="minEvictableIdleTimeMillis" value="300000" /><!-- 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3 --><property name="numTestsPerEvictionRun" value="3" /><!-- “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1. --><property name="timeBetweenEvictionRunsMillis" value="60000" /><!-- testOnBorrow:向调用者输出“链接”资源时,是否检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取。默认为false。建议保持默认值. --><!-- testOnReturn:向连接池“归还”链接时,是否检测“链接”对象的有效性。默认为false。建议保持默认值.--><!-- testWhileIdle:向调用者输出“链接”对象时,是否检测它的空闲超时;默认为false。如果“链接”空闲超时,将会被移除。建议保持默认值. --><!-- whenExhaustedAction:当“连接池”中active数量达到阀值时,即“链接”资源耗尽时,连接池需要采取的手段, 默认为1(0:抛出异常。1:阻塞,直到有可用链接资源。2:强制创建新的链接资源) --></bean><!-- Spring提供的Redis连接工厂 --><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"><!-- 连接池配置. --><property name="poolConfig" ref="jedisPoolConfig" /><!-- Redis服务主机. --><property name="hostName" value="192.168.110.101" /><!-- Redis服务端口号. --><property name="port" value="6379" /><!-- Redis服务连接密码. --><!-- <property name="password" value="${redis.password}" /> --><!-- 连超时设置. --><property name="timeout" value="15000" /><!-- 是否使用连接池. --><property name="usePool" value="true" /></bean><!-- Spring提供的访问Redis类. --><bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"><property name="connectionFactory" ref="jedisConnectionFactory" /><property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /></property><property name="valueSerializer"><!-- <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> --><bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" /></property></bean></beans>
public static void main(String[] args){ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context-jedis.xml");// 获取Spring提供的RedisTemplate类此类封装了Jedis,简化操作RedisTemplate<String, List<String>> redisTemplate = applicationContext.getBean("jedisTemplate", RedisTemplate.class);// Spring 提供的各种Redis结构的key-value操作类ValueOperations<String, List<String>> value = redisTemplate.opsForValue();HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();ListOperations<String, List<String>> list = redisTemplate.opsForList();HyperLogLogOperations<String, List<String>> hyperLogLog = redisTemplate.opsForHyperLogLog();SetOperations<String, List<String>> set = redisTemplate.opsForSet();ZSetOperations<String, List<String>> zSet = redisTemplate.opsForZSet();List<String> listValue = new ArrayList<String>();listValue.add("001");listValue.add("002");value.set("list", listValue);System.out.println(value.get("list"));// 关闭Spring容器释放资源applicationContext.close();}
private boolean enableTransactionSupport = false;private boolean exposeConnection = false;private boolean initialized = false;private boolean enableDefaultSerializer = true;// 默认的序列化实现private RedisSerializer<?> defaultSerializer = new JdkSerializationRedisSerializer();// 各种操作的序列化方式定义private RedisSerializer keySerializer = null;private RedisSerializer valueSerializer = null;private RedisSerializer hashKeySerializer = null;private RedisSerializer hashValueSerializer = null;private RedisSerializer<String> stringSerializer = new StringRedisSerializer();private ScriptExecutor<K> scriptExecutor;// Spring 提供的各种Redis结构的key-value操作类// cache singleton objects (where possible)private ValueOperations<K, V> valueOps;private ListOperations<K, V> listOps;private SetOperations<K, V> setOps;private ZSetOperations<K, V> zSetOps;private HyperLogLogOperations<K, V> hllOps;
public ValueOperations<K, V> opsForValue(){if (valueOps == null){valueOps = new DefaultValueOperations<K, V>(this);}return valueOps;}public ListOperations<K, V> opsForList(){if (listOps == null){listOps = new DefaultListOperations<K, V>(this);}return listOps;}// 省略部分......
public void set(K key, V value){final byte[] rawValue = rawValue(value);execute(new ValueDeserializingRedisCallback(key){protected byte[] inRedis(byte[] rawKey, RedisConnection connection){connection.set(rawKey, rawValue);return null;}}, true);}// 省略其他操作......
//org.springframework.data.redis.core.AbstractOperations<K, V><T> T execute(RedisCallback<T> callback, boolean b) {return template.execute(callback, b);}// template.execute实现如下:// org.springframework.data.redis.core.RedisTemplate<K, V>public <T> T execute(RedisCallback<T> action, boolean exposeConnection) {return execute(action, exposeConnection, false);}// execute实现如下:// org.springframework.data.redis.core.RedisTemplate<K, V> --- 最终实现public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");Assert.notNull(action, "Callback object must not be null");RedisConnectionFactory factory = getConnectionFactory();RedisConnection conn = null;try {if (enableTransactionSupport) {// only bind resources in case of potential transaction synchronizationconn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);} else {conn = RedisConnectionUtils.getConnection(factory);}boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);RedisConnection connToUse = preProcessConnection(conn, existingConnection);boolean pipelineStatus = connToUse.isPipelined();if (pipeline && !pipelineStatus) {connToUse.openPipeline();}RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));T result = action.doInRedis(connToExpose);// close pipelineif (pipeline && !pipelineStatus) {connToUse.closePipeline();}// TODO: any other connection processing?return postProcessResult(result, connToUse, existingConnection);} finally {if (!enableTransactionSupport) {RedisConnectionUtils.releaseConnection(conn, factory);}}}
2.JedisConnectionFactory中使用sentinel集群
<!-- Redis sentinel集群配置 --><bean id="sentinelConfig" class="org.springframework.data.redis.connection.RedisSentinelConfiguration"><constructor-arg index="0" type="java.lang.String" value="master001" /><constructor-arg index="1" type="java.util.Set"><set><value>192.168.110.100:26379</value><value>192.168.110.100:36379</value><value>192.168.110.100:46379</value></set></constructor-arg></bean><!-- Spring提供的Redis连接工厂 --><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"><!-- Redis sentinel集群配置 --><constructor-arg index="0" type="org.springframework.data.redis.connection.RedisSentinelConfiguration" ref="sentinelConfig" /><!-- 连接池配置. --><constructor-arg index="1" type="redis.clients.jedis.JedisPoolConfig" ref="jedisPoolConfig" /><!-- Redis服务主机. --><property name="hostName" value="192.168.110.101" /><!-- Redis服务端口号. --><property name="port" value="6379" /><!-- Redis服务连接密码. --><!-- <property name="password" value="${redis.password}" /> --><!-- 连超时设置. --><property name="timeout" value="15000" /><!-- 是否使用连接池. --><property name="usePool" value="true" /></bean>
public static void main(String[] args){ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context-jedis.xml");// 获取Spring提供的RedisTemplate类此类封装了Jedis,简化操作RedisTemplate<String, String> redisTemplate = applicationContext.getBean("jedisTemplate", RedisTemplate.class);ValueOperations<String, String> value = redisTemplate.opsForValue();value.set("K001", "V001");System.out.println(value.get("K001"));// 关闭Redis Master服务Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();System.out.println(input);value.set("K002", "V002");System.out.println(value.get("K002"));// 关闭Spring容器释放资源applicationContext.close();}
2015-10-3 15:10:59 redis.clients.jedis.JedisSentinelPool initSentinels信息: Trying to find master from available Sentinels...2015-10-3 15:10:59 redis.clients.jedis.JedisSentinelPool initSentinels信息: Redis master running at 192.168.110.101:6379, starting Sentinel listeners...2015-10-3 15:10:59 redis.clients.jedis.JedisSentinelPool initPool信息: Created JedisPool to master at 192.168.110.101:6379V0012015-10-3 15:11:38 redis.clients.jedis.JedisSentinelPool initPool信息: Created JedisPool to master at 192.168.110.103:6379V002
3.JedisConnectionFactory中使用JedisShardInfo
- private JedisShardInfo shardInfo;
// 省略......public void afterPropertiesSet() {if (shardInfo == null) {shardInfo = new JedisShardInfo(hostName, port);if (StringUtils.hasLength(password)) {shardInfo.setPassword(password);}if (timeout > 0) {setTimeoutOn(shardInfo, timeout);}}if (usePool) {this.pool = createPool();}}// 省略......protected Jedis fetchJedisConnector() {try {if (usePool && pool != null) {return pool.getResource();}Jedis jedis = new Jedis(getShardInfo());// force initialization (see Jedis issue #82)jedis.connect();return jedis;} catch (Exception ex) {throw new RedisConnectionFailureException("Cannot get Jedis connection", ex);}}
04.spring-data-redis与Jedis整合使用的更多相关文章
- 关于在项目中使用spring data redis与jedis的选择
项目中需要用到redis,主要用来作为缓存,redis的客户端有两种实现方式,一是可以直接调用jedis来实现,二是可以使用spring data redis,通过spring的封装来调用. 应该使用 ...
- Spring Data Redis与Jedis的选择(转)
说明:内容可能有点旧,需要在业务上做权衡. Redis的客户端有两种实现方式,一是可以直接调用Jedis来实现,二是可以使用Spring Data Redis,通过Spring的封装来调用.应该使用哪 ...
- Spring Boot使用Spring Data Redis操作Redis(单机/集群)
说明:Spring Boot简化了Spring Data Redis的引入,只要引入spring-boot-starter-data-redis之后会自动下载相应的Spring Data Redis和 ...
- Spring Data Redis入门示例:基于Jedis及底层API (二)
使用底层API:RedisConnectionFactory和RedisConnection可以直接操作Redis,下面是一个简单的例子: ### Maven依赖 <properties> ...
- spring mvc Spring Data Redis RedisTemplate [转]
http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...
- Spring data redis的使用
Spring data redis的使用 一.Redis的安装和使用 Redis是用C语言开发的一个高性能键值对数据库,可用于数据缓存,主要用于处理大量数据的高访问负载. 下载地址:https://g ...
- Redis与Spring Data Redis
1.Redis概述 1.1介绍 官网:https://redis.io/ Redis是一个开源的使用ANSIC语言编写.支持网络.可基于内存 亦可持久化的日志型.Key-Value型的高性能数据库. ...
- spring data redis RedisTemplate操作redis相关用法
http://blog.mkfree.com/posts/515835d1975a30cc561dc35d spring-data-redis API:http://docs.spring.io/sp ...
- spring data redis使用示例
1. 配置依赖文件 <dependencies> <dependency> <groupId>org.springframework.data</groupI ...
随机推荐
- Git客户端图文详解如何安装配置GitHub操作流程攻略
收藏自 http://www.ihref.com/read-16377.html Git介绍 分布式 : Git版本控制系统是一个分布式的系统, 是用来保存工程源代码历史状态的命令行工具; 保存点 : ...
- 模拟新浪微博textarea,刷新页面输入信息保留
今天我们的产品经理提出一个新需求,模拟新浪微博textarea框,输入内容刷新页面保留信息. 我是用的方法是Html5 LocalStorage存储的,开始计划用cookie.或mysql存储,尝试了 ...
- 记录C++学习历程
从今天开始学习C++,将学习中遇到的问题,以及解决方案记录在这个博客里. 函数 1.C++函数声明(原型) 函数原型跟函数的定义在返回值类型,函数名,参数上必须完全一致. 2.程序的内存区域:全局数据 ...
- Java 第七天 动态代理
代理类需实现InvocationHandler接口: public interface InvocationHandler { public Object invoke(Object proxy,Me ...
- python中读取配置文件ConfigParser
在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介 ...
- golang的++与--
http://godoc.golangtc.com/doc/faq#inc_dec 简单地说, 在golang中++,--操作是语句而不是表达式. 所以a=b++, return x++之类绝对提示错 ...
- Android or iOS 运行 meteor App 屏幕一片空白 White screen的解决方法
在mac上出现这种错误,多是与文件夹的权限有关,有人建议把~/.meteor目录删除,重新下载安装.在墙内重新下载安装的代价非常之大. 简单的解决方法,便是把~/.meteor,以及当前项目目录的权限 ...
- WebApi接口访问频率控制的实现
关于限流的文章,博客园内还是有挺多的.本文做了一个基于Filter限流的例子,算是对WebApiThrottle使用的一个具体的实例. 实现方法: 1.使用Nuget,对WebAPI项目添加WebAp ...
- [转]WinExec、ShellExecute和CreateProcess及返回值判断方式
[转]WinExec.ShellExecute和CreateProcess及返回值判断方式 http://www.cnblogs.com/ziwuge/archive/2012/03/12/23924 ...
- 21.altera fpga 芯片中 pin 和 pad 区别
在chip planner 中 ,看管脚时,会看到 pin 和pad 同时出现, 如 pin120/pad174 Bank 4 那么有什么区别? PIN指芯片封装好后的管脚,即用户看到的管脚: PAD ...