濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > Spring Boot 項(xiàng)目集成Redis的方式詳解

Spring Boot 項(xiàng)目集成Redis的方式詳解

熱門標(biāo)簽:日本中國(guó)地圖標(biāo)注 魔獸2青云地圖標(biāo)注 貴州電銷卡外呼系統(tǒng) 北京400電話辦理收費(fèi)標(biāo)準(zhǔn) 鄭州人工智能電銷機(jī)器人系統(tǒng) 超呼電話機(jī)器人 山東外呼銷售系統(tǒng)招商 宿遷便宜外呼系統(tǒng)平臺(tái) 十堰營(yíng)銷電銷機(jī)器人哪家便宜

集成方式

使用Jedis

Jedis是Redis官方推薦的面向Java的操作Redis的客戶端,是對(duì)服務(wù)端直連后進(jìn)行操作。如果直接使用Jedis進(jìn)行連接,多線程環(huán)境下是非線程安全的,正式生產(chǎn)環(huán)境一般使用連接池進(jìn)行連接。

dependency>
    groupId>redis.clients/groupId>
    artifactId>jedis/artifactId>
    version>2.9.0/version>
/dependency>

使用spring-data-redis

由Spring 框架提供,是對(duì)Redis客戶端的進(jìn)一步封裝,屏蔽了不同客戶端的不同實(shí)現(xiàn)方式,讓服務(wù)端和客戶端進(jìn)一步解耦;也就是你可以切換不同的客戶端實(shí)現(xiàn),比如Jedis或Lettuce(Redis客戶端實(shí)現(xiàn)之一),而不影響你的業(yè)務(wù)邏輯。

類似于的SpringCloud的服務(wù)治理框架對(duì)不同服務(wù)治理組件的適配,或是AMQP

它利用RedisTemplate對(duì)JedisApi進(jìn)行高度封裝。使用的依賴如下:

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

Redis的安裝

​收先要安裝Redis服務(wù)端,Redis官方提供的是Linux安裝包。網(wǎng)上有很多詳細(xì)的安裝教程,這里不做展開(kāi)。關(guān)于Windows下的安裝,可參考我的另一篇博文windows下Redis的安裝和使用

綁定配置

​完成Redis服務(wù)端的安裝之后,我們開(kāi)始在項(xiàng)目中進(jìn)行集成。這里我們先介紹使用Jedis的方式進(jìn)行的集成。先按上面的提及的方式進(jìn)行依賴的引入。然后將Redis的相關(guān)信息配置到配置文件中去。我們可以的新建一個(gè)配置文件redis.properties,內(nèi)容如下:

# Redis數(shù)據(jù)庫(kù)索引(默認(rèn)為0)
spring.redis.database=0
# Redis服務(wù)器地址
spring.redis.host=127.0.0.1
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
# 連接超時(shí)時(shí)間(毫秒)
spring.redis.timeout=0

​接下來(lái)我們要為Redis客戶端連接綁定上面的配置,創(chuàng)建出來(lái)的客戶端實(shí)例才能夠連接到我們的想連的Redis服務(wù)端。你可以使用@Value注解或@ConfigurationProperties注解的方式,本文采用的是后者,如果還不清楚的該注解的用法,可以移步我的另一篇博文@ConfigurationProperties實(shí)現(xiàn)自定義配置綁定查看,這里不做展開(kāi)。

​以下是Redis服務(wù)端信息配置的接收類:MyRedisProperties.java

@ConfigurationProperties(
        prefix = "spring.redis"
)
@Component
@Data
@PropertySource("classpath:/redis.properties")
public class MyRedisProperties {
    private String database;
    private String host;
    private Integer port;
    private String password;
    private Integer timeOut;
}

由于我們正式生產(chǎn)環(huán)境一般都是采用連接池方式實(shí)現(xiàn),所以我們還需要關(guān)于連接池的配置如下:

# 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0

對(duì)應(yīng)的接收類如下:

@ConfigurationProperties(
        prefix = "spring.redis.pool"
)
@Data
@Component
@PropertySource("classpath:/redis.properties")
public class RedisPoolProperties {

    private Integer maxActive;
    private Integer maxWait;
    private Integer maxIdle;
    private Integer minIdle;
}

然后向Spring容器裝配客戶端實(shí)例,分為單個(gè)客戶端和連接池兩種實(shí)現(xiàn),如下代碼:

@Configuration
public class RedisConfig {

    @Autowired
    private RedisPoolProperties redisPoolProperties;
    @Autowired
    private MyRedisProperties myRedisProperties;

    @Bean
    public Jedis singleJedis(){
        return new Jedis(myRedisProperties.getHost(),myRedisProperties.getPort());
    }

    @Bean
    public JedisPool jedisPool(){ 
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());
        poolConfig.setMaxTotal(redisPoolProperties.getMaxActive());
        poolConfig.setMaxWaitMillis(redisPoolProperties.getMaxWait() * 1000);
        JedisPool jp = new JedisPool(poolConfig, myRedisProperties.getHost(), myRedisProperties.getPort(),
                myRedisProperties.getTimeOut()*1000, myRedisProperties.getPassword(), 0);
        return jp;

    }
}

獲取Redis客戶端

進(jìn)行相關(guān)配置的綁定之后,意味著我們程序可以拿到Redis和連接池的相關(guān)信息,然后進(jìn)行客戶端的創(chuàng)建和連接了。所以我們要向Spring容器裝配客戶端實(shí)例,分為單個(gè)客戶端和連接池兩種實(shí)現(xiàn),如下代碼:

@Configuration
public class RedisConfig {

    @Autowired
    private RedisPoolProperties redisPoolProperties;
    @Autowired
    private MyRedisProperties myRedisProperties;

    @Bean
    public Jedis singleJedis(){
        return new Jedis(myRedisProperties.getHost(),myRedisProperties.getPort());
    }

    @Bean
    public JedisPool jedisPool(){ 
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());
        poolConfig.setMaxTotal(redisPoolProperties.getMaxActive());
        poolConfig.setMaxWaitMillis(redisPoolProperties.getMaxWait() * 1000);
        JedisPool jp = new JedisPool(poolConfig, myRedisProperties.getHost(), myRedisProperties.getPort(),
                myRedisProperties.getTimeOut()*1000, myRedisProperties.getPassword(), 0);
        return jp;

    }
}

Redis工具的編寫

裝配好客戶端實(shí)例后,我們就可以通過(guò)@Autowired的方式進(jìn)行注入使用了。我們都知道,Redis有5中數(shù)據(jù)類型,分別是:

  • string(字符串)
  • hash(哈希)
  • list(列表)
  • set(集合)
  • zset(sorted set:有序集合)

所以的有必要的封裝一個(gè)操作者5種數(shù)據(jù)列表的工具類,由于篇幅的關(guān)系,我們以Redis最基本的數(shù)據(jù)類型String為例,簡(jiǎn)單封裝幾個(gè)操作方法作為示例如下,更詳細(xì)的封裝,可參考java操作Redis數(shù)據(jù)庫(kù)的redis工具,RedisUtil,jedis工具JedisUtil,JedisPoolUtil這一博文

@Service
public class RedisService {

    @Autowired
    private JedisPool jedisPool; // 連接池方式
    @Autowired
    private Jedis myJedis; // 單個(gè)客戶端

    public T> T get(String key, ClassT> clazz) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String str = jedis.get(key);
            return stringToBean(str,clazz);
        } finally {
            close(jedis);
        }
    }

    public T> void set(String key, T value) {
        try {
            String str = value.toString();
            if (str == null || str.length() = 0) {
                return;
            }
            myJedis.set(key, str);
        } finally {
            close(myJedis);
        }
    }

    private void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 把一個(gè)字符串轉(zhuǎn)換成bean對(duì)象
     * @param str
     * @param T>
     * @return
     */
    public static T> T stringToBean(String str, ClassT> 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);
        }
    }
}

其中get方法使用連接池中的客戶端實(shí)例,set方法用到的是非連接池的實(shí)例,以區(qū)分兩種不同的使用方式

使用

封裝好的Redis的操作工具類后,我們就可以直接使用該工具類來(lái)進(jìn)行對(duì)Redis的各種操作 。如下,直接注入即可。

@RestController
public class TestController {

    @Autowired
    private RedisService redisService;
    
    ......
}

到此這篇關(guān)于Spring Boot 項(xiàng)目集成Redis的文章就介紹到這了,更多相關(guān)Spring Boot 項(xiàng)目集成Redis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • 使用SpringBoot集成redis的方法
  • SpringBoot集成Redis實(shí)現(xiàn)消息隊(duì)列的方法
  • Spring boot集成redis lettuce代碼實(shí)例
  • 基于SpringBoot集成測(cè)試遠(yuǎn)程連接Redis服務(wù)的教程詳解
  • springboot集成redis實(shí)現(xiàn)簡(jiǎn)單秒殺系統(tǒng)
  • SpringBoot集成Redisson實(shí)現(xiàn)分布式鎖的方法示例
  • springBoot集成redis的key,value序列化的相關(guān)問(wèn)題

標(biāo)簽:楊凌 果洛 朝陽(yáng) 臺(tái)州 北京 吉安 江蘇 大慶

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Spring Boot 項(xiàng)目集成Redis的方式詳解》,本文關(guān)鍵詞  Spring,Boot,項(xiàng)目,集成,Redis,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Spring Boot 項(xiàng)目集成Redis的方式詳解》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于Spring Boot 項(xiàng)目集成Redis的方式詳解的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    绥棱县| 太谷县| 青神县| 华池县| 贵南县| 永宁县| 康马县| 屏南县| 东山县| 循化| 石门县| 牡丹江市| 台东县| 惠东县| 文化| 当阳市| 涪陵区| 西城区| 慈溪市| 浦县| 徐闻县| 宜川县| 宾川县| 扎兰屯市| 新乡县| 成武县| 龙岩市| 高邮市| 天气| 佛冈县| 德兴市| 东平县| 西藏| 湘阴县| 台安县| 兴海县| 宁远县| 香港 | 三穗县| 兴国县| 丰都县|