Springboot整合Redisson


基本配置參考這個博客:

https://blog.csdn.net/vistaed/article/details/107026758

本人使用的springboot版本是2.1.5

依賴如下:

<dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson-spring-boot-starter</artifactId>
        <version>3.13.1</version>
        <exclusions>
          <exclusion>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-data-22</artifactId>
          </exclusion>
        </exclusions>
      </dependency>

      <dependency>
        <groupId>org.redisson</groupId>
        <!-- for Spring Data Redis v.2.1.x -->
        <artifactId>redisson-spring-data-21</artifactId>
        <version>3.13.1</version>
      </dependency>

 

 

 

所以要向上面那樣,先排除掉redisson-spring-data-22   再單獨加入

redisson-spring-data-21


之后,在resource下面加入redisson-single.yml配置文件

 

 
        

 內容如下:可以參考官網:https://github.com/redisson/redisson/wiki/2.-Configuration#221-yaml-file-based-configuration

 
        
# 單節點配置
singleServerConfig:
  # 連接空閑超時,單位:毫秒
  idleConnectionTimeout: 10000
  # 連接超時,單位:毫秒
  connectTimeout: 10000
  # 命令等待超時,單位:毫秒
  timeout: 3000
  # 命令失敗重試次數,如果嘗試達到 retryAttempts(命令失敗重試次數) 仍然不能將命令發送至某個指定的節點時,將拋出錯誤。
  # 如果嘗試在此限制之內發送成功,則開始啟用 timeout(命令等待超時) 計時。
  retryAttempts: 3
  # 命令重試發送時間間隔,單位:毫秒
  retryInterval: 1500
  #  # 重新連接時間間隔,單位:毫秒
  #  reconnectionTimeout: 3000
  #  # 執行失敗最大次數
  #  failedAttempts: 3
  # 密碼
  password: 1234
  # 單個連接最大訂閱數量
  subscriptionsPerConnection: 5
  # 客戶端名稱
  clientName: null
  #  # 節點地址
  address: "redis://127.0.0.1:6379"
  # 發布和訂閱連接的最小空閑連接數
  subscriptionConnectionMinimumIdleSize: 1
  # 發布和訂閱連接池大小
  subscriptionConnectionPoolSize: 50
  # 最小空閑連接數
  connectionMinimumIdleSize: 500
  # 連接池大小
  connectionPoolSize: 1000
  # 數據庫編號
  database: 0
  # DNS監測時間間隔,單位:毫秒
  dnsMonitoringInterval: 5000
# 線程池數量,默認值: 當前處理核數量 * 2
threads: 16
# Netty線程池數量,默認值: 當前處理核數量 * 2
nettyThreads: 32
# 編碼,不使用默認編碼,因為set進去之后是亂碼
#codec: !<org.redisson.codec.MarshallingCodec> {}
# 傳輸模式
transportMode : "NIO"

配置Redisson參考了:https://blog.csdn.net/atu1111/article/details/106325258?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.highlightwordscore&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.highlightwordscore
import java.io.IOException;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.Codec;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class RedssonConfig {
    // 加載配置文件,裝配RedissonClient
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws IOException {
        Config config = Config.fromYAML(new ClassPathResource("redisson-single.yml").getInputStream());
        Codec codec=new FastJsonCodec();
        config.setCodec(codec);
        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }
}

 

codc就是編碼方式,這里用fastjson實現了一個,參考:https://blog.csdn.net/miaochenfly/article/details/116457365?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-1-116457365.pc_agg_new_rank&utm_term=redisson%E5%A6%82%E4%BD%95%E5%BA%8F%E5%88%97%E5%8C%96&spm=1000.2123.3001.4430

import java.io.IOException;
import java.nio.charset.Charset;

import org.redisson.client.codec.BaseCodec;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;

public class FastJsonCodec extends BaseCodec {
    // 開啟對於AutoType的支持
    // https://github.com/alibaba/fastjson/wiki/enable_autotype
    public static final ParserConfig defaultConfig = new ParserConfig();
    static {
        defaultConfig.setAutoTypeSupport(true);
    }
    private final Encoder encoder = in -> {
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        try {
            ByteBufOutputStream os = new ByteBufOutputStream(out);
            JSON.writeJSONString(os, in, SerializerFeature.WriteClassName);
            return os.buffer();
        } catch (IOException e) {
            out.release();
            throw e;
        } catch (Exception e) {
            out.release();
            throw new IOException(e);
        }
    };

    private final Decoder<Object> decoder = (buf, state) ->
            JSON.parseObject(new ByteBufInputStream(buf), Charset.forName("UTF-8"),
                    Object.class, defaultConfig);
            //JSON.parseObject(new ByteBufInputStream(buf), Object.class);

    @Override
    public Decoder<Object> getValueDecoder() {
        return decoder;
    }

    @Override
    public Encoder getValueEncoder() {
        return encoder;
    }
}

 

 
        

測試:可以直接把接口返回值改成LoginVo,參數都是String類型,電話號碼和密碼,不貼了

import java.util.concurrent.TimeUnit;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.dk.su.common.result.Result;
import cn.dk.su.common.rpc.user.vo.LoginVo;

@Controller
@RequestMapping("/redisson")
public class TestRedisson {
    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping(value = "/set", method = RequestMethod.GET)
    @ResponseBody
    public Result<LoginVo> set() {
        RBucket<LoginVo> bucket = redissonClient.getBucket("key");
        LoginVo loginVo = new LoginVo();
        loginVo.setPassword("222222");
        loginVo.setTelephone("13000000000");
        bucket.set(loginvo, 2, TimeUnit.MINUTES);
        return Result.success(bucket.get());
    }
  // 下面這倆函數實際上沒用到
    public static <T> String beanToString(T value) {
        if (value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if (clazz == int.class || clazz == Integer.class) {
            return "" + value;
        } else if (clazz == String.class) {
            return (String) value;
        } else if (clazz == long.class || clazz == Long.class) {
            return "" + value;
        } else {
            return JSON.toJSONString(value);
        }
    }

    // 獲得value之后,將String轉化為類對象
    public static <T> T stringToBean(String str, Class<T> clazz) {
        if (str == null || str.length() <= 0 || clazz == null) {
            return null;
        }
        if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else if (clazz == long.class || clazz == Long.class) {
            return  (T) Long.valueOf(str);
        } else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }
}

 

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM