欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2021年08月23日 10:02:41   作者:Acelin_H''''''''''''''''''''''''''''''''s Blog  
這篇文章主要介紹了Spring Boot 項(xiàng)目集成Redis的方式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧,需要的朋友可以參考下

集成方式

使用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工具的編寫(xiě)

裝配好客戶端實(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, Class<T> 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, 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);
        }
    }
}

其中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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論