首頁 > 軟體

spring boot整合redis中介軟體與熱部署實現程式碼

2023-02-01 18:02:54

熱部署

每次寫完程式後都需要重啟伺服器,需要大量的時間,spring boot提供了一款工具devtools幫助實現熱部署。

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
     <optional>true</optional> <!-- 可選 -->
 </dependency>

匯入外掛的以來後每次點選 ---->構建------>構建專案就可以了,相比重啟要快的多。

Redis

spring boot整合redis最常用的有三個工具庫Jedis,Redisson,Lettuce

共同點:都提供了基於 Redis 操作的 Java API,只是封裝程度,具體實現稍有不同。

不同點:

Jedis是 Redis 的 Java 實現的使用者端。支援基本的資料型別如:String、Hash、List、Set、Sorted Set。
特點:使用阻塞的 I/O,方法呼叫同步,程式流需要等到 socket 處理完 I/O 才能執行,不支援非同步操作。Jedis 使用者端範例不是執行緒安全的,需要通過連線池來使用 Jedis。

Redisson
優點點:分散式鎖,分散式集合,可通過 Redis 支援延遲佇列。

Lettuce
用於執行緒安全同步,非同步和響應使用,支援叢集,Sentinel,管道和編碼器。
基於 Netty 框架的事件驅動的通訊層,其方法呼叫是非同步的。Lettuce 的 API 是執行緒安全的,所以可以操作單個 Lettuce 連線來完成各種操作。

Jedis

引入依賴

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


<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.1.0</version>
</dependency>

組態檔

# Redis伺服器地址
spring.data.redis.host=192.168.223.128
# Redis伺服器連線埠
spring.data.redis.port=6379
# Redis伺服器連線密碼(預設為空)
spring.data.redis.password=root

注意時spring.data.redis而不是spring.redis後者已經捨棄了。

通過jedis連線redis:

import redis.clients.jedis.Jedis;
public class RedisConect {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.223.128",6379);
        //設定連線密碼
        jedis.auth("root");
        String csvfile = jedis.get("csvfile");
        System.out.println(csvfile);
        jedis.close();
    }
}

spring boot 聯合jedis連線redis:

//裝配引數
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.data.redis")
@Data
public class RedisConfig {
    private String host;
    private int port;
    private String password;
}
//建立jedis
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class JedisService {
    @Autowired RedisConfig redisConfig;



    public Jedis defaultJedis(){
        Jedis jedis = new Jedis(redisConfig.getHost(),redisConfig.getPort());
        jedis.auth(redisConfig.getPassword());
        return jedis;
    }
}
//測試
    @Test
    void One(){
        jedisService.defaultJedis().set("one","word");
        String one = jedisService.defaultJedis().get("one");
        System.out.println(one);
    }

RedisTemplate

裝配引數除了上面@ConfigurationProperties的方法還有PropertySource方法:

@Configuration
@PropertySource("classpath:redis.properties")
public class RedisConfig {
 
    @Value("${redis.hostName}")
    private String hostName;
 
    @Value("${redis.password}")
    private String password;
 
    @Value("${redis.port}")

}

RedisTemplate是spring自帶模板,需要設定一些引數:

package com.example.JedsFactory;

import com.example.RedisConfig.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Configuration
@PropertySource("classpath:redis.properties")
public class JedisFactory {

        @Value("${spring.data.redis.host}")
        private String host;

        @Value("${spring.data.redis.password}")
        private String password;

        @Value("${spring.data.redis.port}")
        private Integer port;

        @Bean
        public JedisConnectionFactory JedisConnectionFactory(){
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
            redisStandaloneConfiguration.setHostName(host);
            redisStandaloneConfiguration.setPort(port);
            redisStandaloneConfiguration.setPassword(password);
            JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
            JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration,
                    jedisClientConfiguration.build());
            return factory;
        }

        @Bean
        public RedisTemplate makeRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            return redisTemplate;
        }
}
//redis.properties

# Redis伺服器地址
spring.data.redis.host=192.168.223.128
# Redis伺服器連線埠
spring.data.redis.port=6379
# Redis伺服器連線密碼(預設為空)
spring.data.redis.password=root

測試:

    @Test
    void two(){
        redisTemplate.opsForValue().set("two","hello");
        String two =(String) redisTemplate.opsForValue().get("two");
        System.out.println(two);
    }

Caused by: java.lang.NoClassDefFoundError: redis/clients/util/Pool

如果報錯了,如標題的錯誤說明jedis版本高了,有衝突,降低jedis版本即可。

jedis從3.0.1版本降低到2.9.1版本。

Caused by: java.lang.NumberFormatException: For input string: “port”

Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "port"
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:79) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1339) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.24.jar:5.3.24]
	... 88 common frames omitted
Caused by: java.lang.NumberFormatException: For input string: "port"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_181]
	at java.lang.Integer.parseInt(Integer.java:580) ~[na:1.8.0_181]
	at java.lang.Integer.valueOf(Integer.java:766) ~[na:1.8.0_181]
	at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:211) ~[spring-core-5.3.24.jar:5.3.24]
	at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402) ~[spring-beans-5.3.24.jar:5.3.24]
	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155) ~[spring-beans-5.3.24.jar:5.3.24]

連線redis時出現這個錯誤原因是:

port屬性不能用int接收,改為Integer。

Caused by: java.lang.NumberFormatException: For input string: “port“

到此這篇關於spring boot整合redis中介軟體與熱部署實現的文章就介紹到這了,更多相關spring boot整合redis中介軟體內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com