天天看點

Spring-Boot-Data-Redis 筆記Spring-Boot-Data-Redis 筆記

Spring-Boot-Data-Redis 筆記

文章目錄

  • Spring-Boot-Data-Redis 筆記
    • 一、簡介
    • 二、使用Jedis
      • 2.1 導入依賴
      • 2.2 配置檔案
    • 三、 使用Letture【預設】
      • 3.1 導入依賴
      • 3.2 配置檔案
    • 四、使用案例

一、簡介

二、使用Jedis

2.1 導入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <!-- 排除預設使用的lettuce -->
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- 配置使用Jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
           

2.2 配置檔案

spring:
  redis:
    timeout: 10000 #用戶端逾時時間機關是毫秒 預設是2000
    cluster:
      nodes: [ip address]:7000,[ip address]:7001,[ip address]:7002,[ip address]:7003,[ip address]:7004,[ip address]:7005,[ip address]:7006,[ip address]:7007,[ip address]:7008
      max-redirects: 10
    password: password
#    使用Jedis連接配接池
   jedis:
     pool:
        # 連接配接池中的最大空閑連接配接,預設值也是8。
       max-idle: 500
        # 連接配接池中的最小空閑連接配接,預設值也是0。
       min-idle: 50
        # 如果指派為-1,則表示不限制;如果pool已經配置設定了maxActive個jedis執行個體,則此時pool的狀态為exhausted(耗盡)
       max-active: 1000
        # 等待可用連接配接的最大時間,機關毫秒,預設值為-1,表示永不逾時。如果超過等待時間,則直接抛出JedisConnectionException
       max-wait: 2000
           

三、 使用Letture【預設】

3.1 導入依賴

<!-- 導入依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 此依賴必須添加 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
           

3.2 配置檔案

spring:
  redis:
    timeout: 10000 #用戶端逾時時間機關是毫秒 預設是2000
    cluster:
      nodes: [ip address]:7000,[ip address]:7001,[ip address]:7002,[ip address]:7003,[ip address]:7004,[ip address]:7005,[ip address]:7006,[ip address]:7007,[ip address]:7008
      max-redirects: 10
    password: password
#    使用lettuce連接配接池
    lettuce:
      pool:
        max-active: 1000
        max-idle: 50
        max-wait: 1000
        min-idle: 10
        time-between-eviction-runs: 100000
           

四、使用案例

RedisUtil工具類:
@Component
public class RedisStringUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * set redis: string類型
     *
     * @param key   key
     * @param value value
     */
    public void setString(String key, String value) {
        setString(key, value, -1);
    }

    /**
     * 設定帶過期時間的String資料
     *
     * @param key    key
     * @param value  value
     * @param expire 過期時間,預設為秒
     */
    public void setString(String key, String value, long expire) {
        setString(key, value, expire, TimeUnit.SECONDS);
    }

    /**
     *  設定帶過期時間的String
     * @param key key
     * @param value value
     * @param expire 過期時間
     * @param timeUnit 時間機關
     */
    public void setString(String key, String value, long expire, TimeUnit timeUnit) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set(key, value, expire, timeUnit);
    }

    /**
     * get redis: string類型
     *
     * @param key key
     * @return
     */
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * set redis: hash類型
     *
     * @param key      key
     * @param filedKey filedkey
     * @param value    value
     */
    public void setHash(String key, String filedKey, String value) {
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        hashOperations.put(key, filedKey, value);
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
    }

    /**
     * get redis: hash類型
     *
     * @param key      key
     * @param filedkey filedkey
     * @return
     */
    public String getHash(String key, String filedkey) {
        return (String) stringRedisTemplate.opsForHash().get(key, filedkey);
    }

    /**
     * set redis:list類型
     *
     * @param key   key
     * @param value value
     * @return
     */
    public long setList(String key, String value) {
        ListOperations<String, String> listOperations = stringRedisTemplate.opsForList();
        return listOperations.leftPush(key, value);
    }

    /**
     * get redis:list類型
     *
     * @param key   key
     * @param start start
     * @param end   end
     * @return
     */
    public List<String> getList(String key, long start, long end) {
        return stringRedisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 釋出消息到隊列
     *
     * @param channel 消息channel
     * @param msg     要發送的消息
     * @return 發送結果
     */
    public boolean publish(String channel, String msg) {
        try {
            stringRedisTemplate.convertAndSend(channel, msg);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
           
釋出者釋出消息:
/**
 * redis釋出消息
 */
@PostMapping(value = "/message")
public String sendMessage(String message) {
    boolean redispublishtest = redisUtil.publish("redispublishtest", message);
    return redispublishtest ? "消息:" + message + "發送成功" : "消息:" + message + "發送失敗";
}
           
消息訂閱者實作消息訂閱:
@Configuration
public class RedisListenersConfig {

    /**
     * 可以傳遞多個 MessageListenerAdapter
     * @param lettuceConnectionFactory  配置使用LettuceConnectionFactory
     * @param redisQueueListenerAdapter 需要添加的擴充卡,可以添加多個
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory lettuceConnectionFactory, MessageListenerAdapter redisQueueListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(lettuceConnectionFactory);
        //添加消息監聽器,實作消息監聽
        container.addMessageListener(redisQueueListenerAdapter, new PatternTopic("redispublishtest"));
        //可以實作添加多個擴充卡
        //container.addMessageListener(marketquelistener, new PatternTopic("marketdata"));
        return container;
    }
    /**
     * 綁定消息監聽者和接收監聽的方法,必須要注入這個監聽器,不然會報錯
     */
    @Bean
    public MessageListenerAdapter redisQueueListenerAdapter(RedisQueueListener redisQueueListener){
        return new MessageListenerAdapter(redisQueueListener,"receiveMessage");
    }

    @Bean
    RedisQueueListener redisQueueListener(){
        return new RedisQueueListener();
    }
}
           
/** 接口實作類,實作接收消息之後處理的方法 **/
public class RedisQueueListener implements RedisQueueListenerInterface {
    @Override
    public void receiveMessage(String message) {
        System.out.println(message);
    }
}
           
/** 消息訂閱接口 定義處理方法 **/
public interface RedisQueueListenerInterface {
    void receiveMessage(String message);
}
           
調用案例:
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisStringUtil redisUtil;

    /**
     * 存儲資料
     */
    @PostMapping(value = "/test/{key}")
    public JsonResult test(@PathVariable("key") String key, String value) {
        redisUtil.setString(key, value);
        return JsonResult.OK();
    }

    /**
     * 擷取資料
     *
     * @param key
     * @return
     */
    @GetMapping(value = "/test/{key}")
    public JsonResult test(@PathVariable("key") String key) {
        Object o = redisUtil.getString(key);
        return JsonResult.OK(o);
    }

    /**
     * redis釋出消息
     */
    @PostMapping(value = "/message")
    public String sendMessage(String message) {
        boolean redispublishtest = redisUtil.publish("redispublishtest", message);
        return redispublishtest ? "消息:" + message + "發送成功" : "消息:" + message + "發送失敗";
    }

    /**
     * 模拟發送手機驗證碼
     */
    @PostMapping(value = "/vcode")
    public String sendVerifyCode(String mobile){
        redisUtil.setString("vcode"+mobile, "123456",10);
        return "驗證碼發送成功";
    }

    /**
     * 模拟接收手機驗證碼
     */
    @GetMapping(value = "/vcode")
    public String getVerifyCode(String mobile){
        String hash = redisUtil.getString("vcode"+mobile);
        return hash;
    }
}
           

繼續閱讀