Spring Boot使用Spring Data Redis操作Redis(單機/集群)


說明:Spring Boot簡化了Spring Data Redis的引入,只要引入spring-boot-starter-data-redis之后會自動下載相應的Spring Data Redis和Jedis客戶端,可以減少版本這塊的沖突,當然,如果要引入別的版本也是可以的。版本控制全部交由Parent引入的Spring Boot節點進行管理!,建議不要引入最新版本的spring-boot-starter-data-redis,避免造成其它沖突。

有個假設:如果在使用Spring/Spring MVC項目時引入的Spring Data Redis和Jedis客戶端時如果存在版本問題,出現莫名奇怪的問題,那么可以使用Spring Boot每個版本對應使用的Spring Data Redis和Jedis。

Spring Boot下面使用Spring Data Redis相當的簡單,只需要引入Spring Data Redis和在配置文件application.properties中配置地址即可,因為它有spring-boot-autoconfigure來實現了自動注入。

下面是實際項目例子:

POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jsoft.springboottest</groupId>
    <artifactId>springboottest1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboottest1</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.7.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Add typical dependencies for a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- 熱部署模塊 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
        </dependency>
        
        <!-- Redis -->
        <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
        
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties:

# REDIS(RedisProperties)
# (普通集群,不使用則不用開啟)在群集中執行命令時要遵循的最大重定向數目。
# spring.redis.cluster.max-redirects=
# (普通集群,不使用則不用開啟)以逗號分隔的“主機:端口”對列表進行引導。
# spring.redis.cluster.nodes=
# 連接工廠使用的數據庫索引。
spring.redis.database=0
# 連接URL,將覆蓋主機,端口和密碼(用戶將被忽略),例如:redis://user:password@example.com:6379
spring.redis.url=
# Redis服務器主機。
spring.redis.host=localhost
# 登錄redis服務器的密碼。
spring.redis.password=
# 啟用SSL支持。
spring.redis.ssl=false
# 池在給定時間可以分配的最大連接數。使用負值無限制。
spring.redis.pool.max-active=8
# 池中“空閑”連接的最大數量。使用負值表示無限數量的空閑連接。
spring.redis.pool.max-idle=8
# 連接分配在池被耗盡時拋出異常之前應該阻塞的最長時間量(以毫秒為單位)。使用負值可以無限期地阻止。
spring.redis.pool.max-wait=-1
# 目標為保持在池中的最小空閑連接數。這個設置只有在正面的情況下才有效果。
spring.redis.pool.min-idle=0
# Redis服務器端口。
spring.redis.port=6379
# (哨兵模式,不使用則不用開啟)Redis服務器的名稱。
# spring.redis.sentinel.master=
# (哨兵模式,不使用則不用開啟)主機:端口對的逗號分隔列表。 
# spring.redis.sentinel.nodes=
# 以毫秒為單位的連接超時。
spring.redis.timeout=0

說明:以上是單機版本的,如果是集群的只需要開啟這兩項:

# (普通集群,不使用則不用開啟)在群集中執行命令時要遵循的最大重定向數目。
spring.redis.cluster.max-redirects=
# (普通集群,不使用則不用開啟)以逗號分隔的“主機:端口”對列表進行引導。
spring.redis.cluster.nodes=127.0.0.1:1001,127.0.0.1:1002

注意:一旦開啟了集群模式,那么基於單機的配置就會覆蓋。

提示:可以這么說,上面的配置應該是最全的了。當然上面針對客戶端的操作估計會比較少,比如哨兵模式,分片等等的,因為這些高可用在服務已經做了,如果想要在客戶端實現這些,那么可以重新注入想要實現Bean即可。比如注入建立工廠,實現自己的Session。

使用:

package com.jsoft.springboottest.springboottest1.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    
    @Autowired
    RedisTemplate redisTemplate;
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @RequestMapping("/set")
    public void set() {
        redisTemplate.opsForValue().set("test", "4321");
    }
    
    @RequestMapping("/show")
    public String show(){
        
        logger.info(redisTemplate.opsForValue().get("test").toString());
        return "Hello World";        
    }
}

說明:只需要注入RedisTemplate即可。

使用技巧:

在市面上可能存在兩種個用法,1中是針對opsForValue,另一種是execute的,那么這兩種的使用區別如下:

1、在redistemplate中配置Serializer

ValueOperations<String, User> valueops = redisTemplate.opsForValue();
valueops.set(user.getId(), user);

2、不在redistemplate中配置Serializer,而是在Service的實現類中單獨指定Serializer。

boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
      public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException { 
          RedisSerializer<String> redisSerializer = redisTemplate .getStringSerializer(); 
          byte[] key = redisSerializer.serialize(user.getId());
          byte[] value = redisSerializer.serialize(user.getName()); 
          return redisConnection.setNX(key, value); } }); 
     return result;
}

也就是說這兩者的區別的序列化是自己實現的。

 

示例項目:https://github.com/easonjim/5_java_example/tree/master/springboottest/springboottest6

 

參考:

https://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/reference/htmlsingle/(官方文檔,搜索spring.redis)

http://blog.csdn.net/i_vic/article/details/53081241

http://www.cnblogs.com/ityouknow/p/5748830.html

https://www.cnblogs.com/edwinchen/p/3816938.html


免責聲明!

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



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