1. 程式人生 > 實用技巧 >Redis安裝與使用(SpringBoot)

Redis安裝與使用(SpringBoot)

Redis 安裝與啟動

redis 沒有 Windows 版本的,只能使用Linux系統,所以這裡使用的是虛擬機器執行,後續會補充線上使用redis。

Redis 下載安裝

Redis可前往官網下載,或者在Linux系統中使用命令下載:

$ wget https://download.redis.io/releases/redis-6.0.9.tar.gz

下載完成後進行解壓,編譯。

$ tar xzf redis-6.0.9.tar.gz
$ cd redis-6.0.9
$ make

編譯要用到gcc,所以可能會需要安裝

$ yum install gcc

Redis 啟動

Redis的啟動很簡單,只需要在redis目錄下執行命令即可

$ ./src/redis-server redis.conf 

可以使用命令開啟自帶的客戶端

$ ./src/redis-cli

Redis配置

Redis的配置檔案就是redis.conf ,啟動時的引數就是配置檔案。

Redis預設不適宜守護程序的方式啟動的,需要在配置檔案中進行配置,下面簡單介紹幾個常用配置

daemonize yes # 預設是no,以非守護程序方式啟動
port 6379 # 埠號,預設值
logfile 'redis.log' #日誌檔案,預設為``空
databases 256 #redis資料庫總量,預設16
requirepass 123456 #設定密碼,預設為被註釋
bind 127.0.0.1 #繫結本機,不允許其他主機連線,需要註釋掉
protected-mode no #安全模式,需要遠端連線時,要設定密碼或者設為no,預設為yes

處理上面這些配置,如果需要遠端使用redis,還有開啟防火牆,並放行相應的埠

$ iptables -I INPUT 1 -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT

Redis 在SpringBoot中的使用

  1. 引入依賴

    <!--Redis 依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!--SpringBoot 快取依賴-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>2.
    
  2. 配置Redis

    spring.redis.host=192.168.247.128
    spring.redis.port=6379
    # spring.redis.password=pass
    
    @Configuration
    @EnableCaching
    public class CacheConfig {
        @Bean
        public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
            RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
            RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
            cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));
    
            RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,
                    cacheConfiguration);
            return redisCacheManager;
        }
    }
    
  3. 添加註解:主方法開啟快取,對應的快取添加註解

    // 主方法新增
    @EnableCaching
    // 啟用快取的方法新增(ServiceImpl)
    @Cacheable(value = "categoryList")
    public List<CategoryVO> selectCategoryListCustom(){。。。}
    

至此,Redis已經可以成功使用,如果有問題,首先檢視redis.conf配置檔案,再檢查防火牆和iptables