Spring Boot教程(三十四)使用Redis資料庫(2)

來源:互聯網
上載者:User

標籤:實驗   exception   uid   data-   template   setvalue   tar   ret   boot   

除了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執行個體
    @Configurationpublic 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 {@Autowiredprivate RedisTemplate<String, User> redisTemplate;@Testpublic 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。

  • 源碼來源

Spring Boot教程(三十四)使用Redis資料庫(2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.