• Spring Boot教程(三十四)使用Redis数据库(2)


    除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplate<String, User>来初始化并进行操作。但是Spring Boot并不支持直接使用,需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化,下面我们通过一个实例来完成对象的读写操作。

    • 创建要存储的对象:User
      public class User implements Serializable {
      
          private static final long serialVersionUID = -1L;
      
          private String username;
          private Integer age;
      
          public User(String username, Integer age) {
              this.username = username;
              this.age = age;
          }
      
          // 省略getter和setter
      
      }
      

        

    • 实现对象的序列化接口
      public class RedisObjectSerializer implements RedisSerializer<Object> {
      
        private Converter<Object, byte[]> serializer = new SerializingConverter();
        private Converter<byte[], Object> deserializer = new DeserializingConverter();
      
        static final byte[] EMPTY_ARRAY = new byte[0];
      
        public Object deserialize(byte[] bytes) {
          if (isEmpty(bytes)) {
            return null;
          }
      
          try {
            return deserializer.convert(bytes);
          } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
          }
        }
      
        public byte[] serialize(Object object) {
          if (object == null) {
            return EMPTY_ARRAY;
          }
      
          try {
            return serializer.convert(object);
          } catch (Exception ex) {
            return EMPTY_ARRAY;
          }
        }
      
        private boolean isEmpty(byte[] data) {
          return (data == null || data.length == 0);
        }
      }
       
      

        

    • 配置针对User的RedisTemplate实例
      @Configuration
      public class RedisConfig {
      
          @Bean
          JedisConnectionFactory jedisConnectionFactory() {
              return new JedisConnectionFactory();
          }
      
          @Bean
          public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
              RedisTemplate<String, User> template = new RedisTemplate<String, User>();
              template.setConnectionFactory(jedisConnectionFactory());
              template.setKeySerializer(new StringRedisSerializer());
              template.setValueSerializer(new RedisObjectSerializer());
              return template;
          }
      
      
      }
       
      

        

       
    • 完成了配置工作后,编写测试用例实验效果
      @RunWith(SpringJUnit4ClassRunner.class)
      @SpringApplicationConfiguration(Application.class)
      public class ApplicationTests {
      
      	@Autowired
      	private RedisTemplate<String, User> redisTemplate;
      
      	@Test
      	public void test() throws Exception {
      
      		// 保存对象
      		User user = new User("超人", 20);
      		redisTemplate.opsForValue().set(user.getUsername(), user);
      
      		user = new User("蝙蝠侠", 30);
      		redisTemplate.opsForValue().set(user.getUsername(), user);
      
      		user = new User("蜘蛛侠", 40);
      		redisTemplate.opsForValue().set(user.getUsername(), user);
      
      		Assert.assertEquals(20, redisTemplate.opsForValue().get("超人").getAge().longValue());
      		Assert.assertEquals(30, redisTemplate.opsForValue().get("蝙蝠侠").getAge().longValue());
      		Assert.assertEquals(40, redisTemplate.opsForValue().get("蜘蛛侠").getAge().longValue());
      
      	}
      
      }
      

        

      当然spring-data-redis中提供的数据操作远不止这些,本文仅作为在Spring Boot中使用redis时的配置参考,更多对于redis的操作使用,请参考Spring-data-redis Reference

    • 源码来源

  • 相关阅读:
    Java实现各种内部排序算法
    Java实现堆排序(大根堆)
    Java对象的序列化和反序列化
    Java实现链式存储的二叉查找树(递归方法)
    337. House Robber III(包含I和II)
    318. Maximum Product of Word Lengths
    114. Flatten Binary Tree to Linked List
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    96. Unique Binary Search Trees(I 和 II)
  • 原文地址:https://www.cnblogs.com/allalongx/p/8526776.html
Copyright © 2020-2023  润新知