spring-data-redis与Jedis整合使用

回到顶部

1.spring-data-redis与Jedis简单整合

spring-data-redis与Jedis简单整合,Redis没有任何集群只是单节点工作,使用连接池
1.创建spring-context-jedis.xml配置文件
   
   
     
     
     
     
  1. xml version="1.0" encoding="UTF-8"?>
  2. xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/mvc
  8. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-4.0.xsd"
  13. default-lazy-init="false">
  14. id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
  15. name="maxTotal" value="8" />
  16. name="maxIdle" value="4" />
  17. name="minIdle" value="1" />
  18. name="maxWaitMillis" value="5000" />
  19. name="minEvictableIdleTimeMillis" value="300000" />
  20. name="numTestsPerEvictionRun" value="3" />
  21. name="timeBetweenEvictionRunsMillis" value="60000" />
  22. id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
  23. name="poolConfig" ref="jedisPoolConfig" />
  24. name="hostName" value="192.168.110.101" />
  25. name="port" value="6379" />
  26. name="timeout" value="15000" />
  27. name="usePool" value="true" />
  28. id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  29. name="connectionFactory" ref="jedisConnectionFactory" />
  30. name="keySerializer">
  31. class="org.springframework.data.redis.serializer.StringRedisSerializer" />
  32. name="valueSerializer">
  33. class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
2.使用Spring提供的RedisTemplate类
   
   
     
     
     
     
  1. public static void main(String[] args)
  2. {
  3. ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context-jedis.xml");
  4. // 获取Spring提供的RedisTemplate类此类封装了Jedis,简化操作
  5. RedisTemplate<String, List<String>> redisTemplate = applicationContext.getBean("jedisTemplate", RedisTemplate.class);
  6. // Spring 提供的各种Redis结构的key-value操作类
  7. ValueOperations<String, List<String>> value = redisTemplate.opsForValue();
  8. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  9. ListOperations<String, List<String>> list = redisTemplate.opsForList();
  10. HyperLogLogOperations<String, List<String>> hyperLogLog = redisTemplate.opsForHyperLogLog();
  11. SetOperations<String, List<String>> set = redisTemplate.opsForSet();
  12. ZSetOperations<String, List<String>> zSet = redisTemplate.opsForZSet();
  13. List<String> listValue = new ArrayList<String>();
  14. listValue.add("001");
  15. listValue.add("002");
  16. value.set("list", listValue);
  17. System.out.println(value.get("list"));
  18. // 关闭Spring容器释放资源
  19. applicationContext.close();
  20. }
3.关于RedisTemplate类源码学习
RedisTemplate类的属性
   
   
     
     
     
     
  1. private boolean enableTransactionSupport = false;
  2. private boolean exposeConnection = false;
  3. private boolean initialized = false;
  4. private boolean enableDefaultSerializer = true;
  5. // 默认的序列化实现
  6. private RedisSerializer defaultSerializer = new JdkSerializationRedisSerializer();
  7. // 各种操作的序列化方式定义
  8. private RedisSerializer keySerializer = null;
  9. private RedisSerializer valueSerializer = null;
  10. private RedisSerializer hashKeySerializer = null;
  11. private RedisSerializer hashValueSerializer = null;
  12. private RedisSerializer<String> stringSerializer = new StringRedisSerializer();
  13. private ScriptExecutor<K> scriptExecutor;
  14. // Spring 提供的各种Redis结构的key-value操作类
  15. // cache singleton objects (where possible)
  16. private ValueOperations<K, V> valueOps;
  17. private ListOperations<K, V> listOps;
  18. private SetOperations<K, V> setOps;
  19. private ZSetOperations<K, V> zSetOps;
  20. private HyperLogLogOperations<K, V> hllOps;
在一个应用中RedisTemplate类对象可以是单例的,因为其属性“ valueOpslistOpssetOpszSetOpshllOps ”的各种操作也是线程安全的,源码如下:
获取其 valueOps listOps setOps zSetOps hllOps 属性:
   
   
     
     
     
     
  1. public ValueOperations<K, V> opsForValue()
  2. {
  3. if (valueOps == null)
  4. {
  5. valueOps = new DefaultValueOperations<K, V>(this);
  6. }
  7. return valueOps;
  8. }
  9. public ListOperations<K, V> opsForList()
  10. {
  11. if (listOps == null)
  12. {
  13. listOps = new DefaultListOperations<K, V>(this);
  14. }
  15. return listOps;
  16. }
  17. // 省略部分......
其属性“ valueOps listOps setOps zSetOps hllOps ”的各种操作也是线程安全的,例如 valueOps 属性对象默认实现类 DefaultValueOperations < K , V > 源码:
   
   
     
     
     
     
  1. public void set(K key, V value)
  2. {
  3. final byte[] rawValue = rawValue(value);
  4. execute(new ValueDeserializingRedisCallback(key)
  5. {
  6. protected byte[] inRedis(byte[] rawKey, RedisConnection connection)
  7. {
  8. connection.set(rawKey, rawValue);
  9. return null;
  10. }
  11. }, true);
  12. }
  13. // 省略其他操作......
再看看 execute 的实现如下:
   
   
     
     
     
     
  1. //org.springframework.data.redis.core.AbstractOperations
  2. <T> T execute(RedisCallback<T> callback, boolean b) {
  3. return template.execute(callback, b);
  4. }
  5. // template.execute实现如下:
  6. // org.springframework.data.redis.core.RedisTemplate
  7. public <T> T execute(RedisCallback<T> action, boolean exposeConnection) {
  8. return execute(action, exposeConnection, false);
  9. }
  10. // execute实现如下:
  11. // org.springframework.data.redis.core.RedisTemplate --- 最终实现
  12. public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
  13. Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
  14. Assert.notNull(action, "Callback object must not be null");
  15. RedisConnectionFactory factory = getConnectionFactory();
  16. RedisConnection conn = null;
  17. try {
  18. if (enableTransactionSupport) {
  19. // only bind resources in case of potential transaction synchronization
  20. conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
  21. } else {
  22. conn = RedisConnectionUtils.getConnection(factory);
  23. }
  24. boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
  25. RedisConnection connToUse = preProcessConnection(conn, existingConnection);
  26. boolean pipelineStatus = connToUse.isPipelined();
  27. if (pipeline && !pipelineStatus) {
  28. connToUse.openPipeline();
  29. }
  30. RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
  31. T result = action.doInRedis(connToExpose);
  32. // close pipeline
  33. if (pipeline && !pipelineStatus) {
  34. connToUse.closePipeline();
  35. }
  36. // TODO: any other connection processing?
  37. return postProcessResult(result, connToUse, existingConnection);
  38. } finally {
  39. if (!enableTransactionSupport) {
  40. RedisConnectionUtils.releaseConnection(conn, factory);
  41. }
  42. }
  43. }
此时已经可以看出每次操作都会创建一个新的 RedisConnection 对象使用完成会调用 RedisConnectionUtils . releaseConnection ( conn , factory ) 方法释放连接,若想查看其创建 RedisConnection 连接和 RedisConnectionUtils . releaseConnection ( conn , factory ) 释放连接过程可继续查看其源码,此处就不赘述了。
回到顶部

2.JedisConnectionFactory中使用sentinel集群

1.在 spring-context-jedis.xml中配置sentinel信息
   
   
     
     
     
     
  1. id="sentinelConfig" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
  2. index="0" type="java.lang.String" value="master001" />
  3. index="1" type="java.util.Set">
  4. 192.168.110.100:26379
  5. 192.168.110.100:36379
  6. 192.168.110.100:46379
  7. id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
  8. index="0" type="org.springframework.data.redis.connection.RedisSentinelConfiguration" ref="sentinelConfig" />
  9. index="1" type="redis.clients.jedis.JedisPoolConfig" ref="jedisPoolConfig" />
  10. name="hostName" value="192.168.110.101" />
  11. name="port" value="6379" />
  12. name="timeout" value="15000" />
  13. name="usePool" value="true" />
2.使用测试代码
   
   
     
     
     
     
  1. public static void main(String[] args)
  2. {
  3. ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context-jedis.xml");
  4. // 获取Spring提供的RedisTemplate类此类封装了Jedis,简化操作
  5. RedisTemplate<String, String> redisTemplate = applicationContext.getBean("jedisTemplate", RedisTemplate.class);
  6. ValueOperations<String, String> value = redisTemplate.opsForValue();
  7. value.set("K001", "V001");
  8. System.out.println(value.get("K001"));
  9. // 关闭Redis Master服务
  10. Scanner scanner = new Scanner(System.in);
  11. String input = scanner.nextLine();
  12. System.out.println(input);
  13. value.set("K002", "V002");
  14. System.out.println(value.get("K002"));
  15. // 关闭Spring容器释放资源
  16. applicationContext.close();
  17. }
代码输出,注意中间的打印:
   
   
     
     
     
     
  1. 2015-10-3 15:10:59 redis.clients.jedis.JedisSentinelPool initSentinels
  2. 信息: Trying to find master from available Sentinels...
  3. 2015-10-3 15:10:59 redis.clients.jedis.JedisSentinelPool initSentinels
  4. 信息: Redis master running at 192.168.110.101:6379, starting Sentinel listeners...
  5. 2015-10-3 15:10:59 redis.clients.jedis.JedisSentinelPool initPool
  6. 信息: Created JedisPool to master at 192.168.110.101:6379
  7. V001
  8. 2015-10-3 15:11:38 redis.clients.jedis.JedisSentinelPool initPool
  9. 信息: Created JedisPool to master at 192.168.110.103:6379
  10. V002
回到顶部

3.JedisConnectionFactory中使用JedisShardInfo

Spring-Data-Redis好像并不支持Redis分片集群,但是JedisConnectionFactory源码中有一个JedisShardInfo属性,源码如下:
   
   
     
     
     
     
  1. private JedisShardInfo shardInfo;
  2. // 省略......
  3. public void afterPropertiesSet() {
  4. if (shardInfo == null) {
  5. shardInfo = new JedisShardInfo(hostName, port);
  6. if (StringUtils.hasLength(password)) {
  7. shardInfo.setPassword(password);
  8. }
  9. if (timeout > 0) {
  10. setTimeoutOn(shardInfo, timeout);
  11. }
  12. }
  13. if (usePool) {
  14. this.pool = createPool();
  15. }
  16. }
  17. // 省略......
  18. protected Jedis fetchJedisConnector() {
  19. try {
  20. if (usePool && pool != null) {
  21. return pool.getResource();
  22. }
  23. Jedis jedis = new Jedis(getShardInfo());
  24. // force initialization (see Jedis issue #82)
  25. jedis.connect();
  26. return jedis;
  27. } catch (Exception ex) {
  28. throw new RedisConnectionFailureException("Cannot get Jedis connection", ex);
  29. }
  30. }

你可能感兴趣的:(redis缓存数据库)