溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用SpringBoot實現(xiàn)整合Redis

發(fā)布時間:2020-10-28 14:33:27 來源:億速云 閱讀:844 作者:Leah 欄目:開發(fā)技術(shù)

使用SpringBoot實現(xiàn)整合Redis?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

redis是最常用的緩存數(shù)據(jù)庫,常用于存儲用戶登錄token、臨時數(shù)據(jù)、定時相關(guān)數(shù)據(jù)等。

redis是單線程的,所以redis的操作是原子性的,這樣可以保證不會出現(xiàn)并發(fā)問題。

redis基于內(nèi)存,速度非常快,據(jù)測試,redis讀的速度是110000次/s,寫的速度是81000次/s

本節(jié)介紹SpringBoot引入redis,以及使用RedisTemplate來操作redis數(shù)據(jù)。

一、A Simple Demo-使用SpringBoot連接redis

maven:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

yml:

server:
 port: 8867
spring:
 redis:
  host: localhost
  port: 6379
  #password: ''
  database: 6

測試類:

@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTest {

  @Autowired
  private RedisTemplate redisTemplate;

  @Test
  public void testRedis() {
    String key = "hello";
    redisTemplate.opsForValue().set("hello", "你好");

    String res = (String) redisTemplate.opsForValue().get(key);
    System.out.println(res);
  }
}

執(zhí)行結(jié)果:

使用SpringBoot實現(xiàn)整合Redis

看一下redis:

使用SpringBoot實現(xiàn)整合Redis

這里存在一個問題:默認的存儲方式導致key在redis-manager里面顯示出來是亂碼的,并且存儲結(jié)果是二進制了。這樣不利用我們查看redis里面的數(shù)據(jù)。

我們需要自定義redis存儲的序列化規(guī)則。

二、解決RedisTemplate默認序列化的問題

完善一下maven:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

定義RedisConfig類:

/**
 * redis配置
 * 主要是配置Redis的序列化規(guī)則,替換默認的jdkSerializer
 * key的序列化規(guī)則用StringRedisSerializer
 * value的序列化規(guī)則用Jackson2JsonRedisSerializer
 */
@Configuration
public class RedisConfig {

  @Bean
  public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(connectionFactory);

    // 使用Jackson2JsonRedisSerialize替換默認序列化
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

    // 設(shè)置key和value的序列化規(guī)則
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

    redisTemplate.afterPropertiesSet();
    return redisTemplate;
  }
}

刪除之前的key,重新執(zhí)行一下test方法:

使用SpringBoot實現(xiàn)整合Redis

下面來演示一下SpringBoot使用RedisTemplate進行redis數(shù)據(jù)的操作

三、基于SpringBoot的redis操作——key/list/hash

RedisTemplate內(nèi)置redis操作如下:

使用SpringBoot實現(xiàn)整合Redis

這里主要展示value/hash/list三種用法:

3.1 RedisTemplate.opsForValue

 @Test
  public void testKeyOps() {
    // 測試redis操作key-value形式
    Set<String> keySet = new HashSet<>();

    String key1 = "name";
    keySet.add(key1);
    // 存儲簡單的key-value,并設(shè)置過期時間
    redisTemplate.opsForValue().set(key1, "eknown", 1, TimeUnit.MINUTES);

    String key2 = "token:user1";
    String key3 = "token:user2";
    keySet.add(key2);
    keySet.add(key3);
    //
    redisTemplate.opsForValue().set(key2, "{\"name\":\"eknown\"}, \"role\":\"admin\"");
    redisTemplate.opsForValue().set(key3, "{\"name\":\"test\"}, \"role\":\"test\"");

    // 根據(jù)key的集合獲取多個value
    List<String> valueList = redisTemplate.opsForValue().multiGet(keySet);
    for (String value : valueList) {
      System.out.println(value);
    }
  }

執(zhí)行結(jié)果:

使用SpringBoot實現(xiàn)整合Redis

redis中的數(shù)據(jù):

使用SpringBoot實現(xiàn)整合Redis

redis中的key顯示出了一個層級關(guān)系,這個小技巧對于實際項目有個非常好的作用:通過prefix:suffix這樣的形式,可以將redis中存儲的數(shù)據(jù)分出層級。

3.2 RedisTemplate.opsForHash

清空該database下的數(shù)據(jù),測試redisTemplate.opsForHash:

  @Test
  public void testHashOps() {
    String key = "hash";
    // 單次往hash中存放一個數(shù)據(jù)
    redisTemplate.opsForHash().put(key, "1", "你好");

    Map<String, Object> map = new HashMap<>();
    map.put("2", "hello");
    map.put("3a", "china1=2");

    // 一次性向hash中存放一個map
    redisTemplate.opsForHash().putAll(key, map);

    // 獲取hash下的所有key和value
    Map<String, Object> resultMap = redisTemplate.opsForHash().entries(key);
    for (String hashKey : resultMap.keySet()) {
      System.out.println(hashKey + ": " + resultMap.get(hashKey));
    }
  }

執(zhí)行結(jié)果:

使用SpringBoot實現(xiàn)整合Redis

redis:

使用SpringBoot實現(xiàn)整合Redis

3.3 RedisTemplate.opsForList

  @Test
  public void testListOps() {
    String listKey = "list";
    redisTemplate.opsForList().leftPush(listKey, "first value"); // 從list最左邊插入數(shù)據(jù)
    redisTemplate.opsForList().leftPush(listKey, "second value but left");
    redisTemplate.opsForList().rightPush(listKey, 3); // 從list最右邊插入數(shù)據(jù)

    List<Object> list = new ArrayList<>();
    list.add("hello");
    list.add("http://www.eknown.cn");
    list.add(23344);
    list.add(false);
    redisTemplate.opsForList().rightPushAll(listKey, list); // 從list右邊批量插入數(shù)據(jù)

    long size = redisTemplate.opsForList().size(listKey);
    if (size > 0) {
      for (int i = 0; i < size -1 ; i++) {
        // 從list最左邊開始讀取list中的數(shù)據(jù),注意pop會導致出棧,也就是數(shù)據(jù)被取出來了(redis中就沒有這個值了)
        // 此處我們讀取size-1條數(shù)據(jù),僅留下最后一條數(shù)據(jù)
        System.out.println(i + ":" + redisTemplate.opsForList().leftPop(listKey).toString());
      }
    }
  }

執(zhí)行上面的腳本,注意在最后的讀取list數(shù)據(jù)代碼前面加一個斷點,此時redis中是這樣的:

使用SpringBoot實現(xiàn)整合Redis

放開斷點,程序繼續(xù)執(zhí)行,控制臺如下:

使用SpringBoot實現(xiàn)整合Redis

注意,此時redis中僅剩余最后一條數(shù)據(jù),這是由于pop的問題,list中的數(shù)據(jù)被讀取并刪除了:

使用SpringBoot實現(xiàn)整合Redis

好了,這一節(jié)主要講了SpringBoot引入redis,以及使用redis的一些基本操作和相關(guān)技巧,在此基礎(chǔ)上,我們可以讓我們的項目變得更加快速、靈活!

關(guān)于使用SpringBoot實現(xiàn)整合Redis問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI