02_Springboot集成Redis【單機(jī)/集群】

@author Jacky wang
轉(zhuǎn)載請(qǐng)注明出處 , http://m.itdecent.cn/p/4cfedabca746

2018年09月12日,第一次補(bǔ)充更新.

看了網(wǎng)上一些Springboot集成Redis的很多資料,發(fā)現(xiàn)對(duì)Redis的配置復(fù)雜了,自己總結(jié)了Springboot集成Redis的簡(jiǎn)單方式。

一. SpringBoot集成Redis單機(jī)版

1.1. 創(chuàng)建Maven工程

搭建SpringBoot工程,包結(jié)構(gòu)如下:

SpringBoot的標(biāo)準(zhǔn)包結(jié)構(gòu)···
3.png

1.2. pom文件添加依賴,properties添加配置

pom.xml :
<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.dream</groupId>
    <artifactId>spring-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Springboot集成Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- Springboot測(cè)試 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 熱部署插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

-----------------------------------------------------------------------------------------------------

application.properties:(很多其實(shí)是默認(rèn)的,這里全部列出來(lái))
    #指定連接工廠使用的Database index,默認(rèn)為: 0
    spring.redis.database=0
    #指定Redis server host,默認(rèn)為: localhost
    spring.redis.host=127.0.0.1
    #指定Redis server的密碼
    #spring.redis.password=
    #指定連接池最大的活躍連接數(shù),-1表示無(wú)限,默認(rèn)為8
    spring.redis.pool.max-active=8
    #指定連接池最大的空閑連接數(shù),-1表示無(wú)限,默認(rèn)為8
    spring.redis.pool.max-idle=8
    #指定當(dāng)連接池耗盡時(shí),新獲取連接需要等待的最大時(shí)間,以毫秒單位,-1表示無(wú)限等待
    spring.redis.pool.max-wait=-1
    #指定連接池中空閑連接的最小數(shù)量,默認(rèn)為0
    spring.redis.pool.min-idle=2
    #指定redis服務(wù)端端口,默認(rèn): 6379
    spring.redis.port=6379
    #指定redis server的名稱
    #spring.redis.sentinel.master
    #指定sentinel節(jié)點(diǎn),逗號(hào)分隔,格式為host:port.
    #spring.redis.sentinel.nodes
    #指定連接超時(shí)時(shí)間,毫秒單位,默認(rèn)為0
    spring.redis.timeout=0

1.3. RedisTemplate的處理

/**
 * Redis數(shù)據(jù)庫(kù)操作對(duì)象
 * @author wwj
 */
@Component
public class RedisClient {

    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 寫入緩存
     * @param key
     * @param value
     * @return
     */
    
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 寫入緩存設(shè)置時(shí)效時(shí)間
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 讀取緩存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    
    /**
     * 判斷緩存中是否有對(duì)應(yīng)的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    
    /**
     * 刪除對(duì)應(yīng)的value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    
    /**
     * 批量刪除對(duì)應(yīng)的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量刪除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }

    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }

    /**
     * 哈希獲取數(shù)據(jù)
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }

    /**
     * 列表獲取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }

    /**
     * 集合獲取
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     * 有序集合獲取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}

到這里就可以使用,RedisClient對(duì)Redis進(jìn)行操作了,上面給出的方法比較全,可以選擇需要用到的進(jìn)行使用。

1.4. 測(cè)試

1.4.1 Application入口類
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
1.4.2 User實(shí)體類
為了測(cè)試,還提供了一個(gè)User實(shí)體類,因?yàn)楫a(chǎn)生了傳輸過(guò)程,因此這里必須要實(shí)現(xiàn)Serializable接口。
public class User implements Serializable {
        private static final long serialVersionUID = 1L;
        private String username;
        private int age;
        
        public User() {
            super();
        }
    
        public User(String username, int age) {
            super();
            this.username = username;
            this.age = age;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User [username=" + username + ", age=" + age + "]";
        }
    }
1.4.3 SpringbootRedisTest測(cè)試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)//指定springboot的啟動(dòng)類
public class SpringBootRedisTest {

    @Autowired
    private RedisClient redisClient;
    
    @Test
    public void testSet() {
        String key = "keyTest";
        String val = "keyVal2";
        redisClient.set(key, val);
        User user = new User("jack", 24);
        redisClient.set("user", user);
    }
    
    @Test
    public void testGet() {
        String key = "keyTest";
        String key2 = "user";
        String val = (String)redisClient.get(key);
        User user = (User)redisClient.get(key2);
        System.err.println(val);
        System.err.println(user);
    }

    @Test
    public void testRemove() {
        String key = "keyTest";
        String key2 = "user";
        redisClient.remove(key);
        redisClient.remove(key2);
    }
    
    @Test
    public void testSetExpire() throws Exception {
        String key = "testExpire";
        String value = "hello";
        long expireTime = 60L;//60秒后消失
        redisClient.set(key, value, expireTime);
    }
}

以上就是Springboot集成Redis的全部過(guò)程,實(shí)現(xiàn)起來(lái)是非常簡(jiǎn)單的。到這里總結(jié)一下:

1. 添加pom.xml : spring-boot-starter-data-redis的依賴
2. 配置application.properties
3. 對(duì)RedisTemplate進(jìn)行部分功能的封裝。

具體的測(cè)試結(jié)果就不貼出來(lái)了,這里貼一下testSetExpire()的結(jié)果。

1.png

二. SpringBoot集成Redis集群版

2.1. SpringBoot集成Redis集群的兩種方式:

2.1.1. SpringBoot內(nèi)置配置支持:

步驟:

  • 引入RedisMaven依賴
  • 配置application.properties支持Redis集群
  • 引入RedisTemplate使用
  • 測(cè)試
1. Maven依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        
2. 配置application.properties支持Redis集群
    # RedisProperties
    # 在群集中執(zhí)行命令時(shí)要遵循的最大重定向數(shù)目。
    spring.redis.cluster.max-redirects=3
    # (普通集群,不使用則不用開(kāi)啟)以逗號(hào)分隔的“主機(jī):端口”對(duì)列表進(jìn)行引導(dǎo)。
    spring.redis.cluster.nodes=192.168.5.122:9001,192.168.5.122:9002
    spring.redis.cluster.timeout=1000\
    
3. 引入RedisTemplate使用
    見(jiàn)單機(jī)版的RedisClient
    
4. 測(cè)試

@SpringBootTest(classes = Application.class)
@RunWith(value = SpringRunner.class)
public class TestRedis {

    @Autowired
    private RedisClient redisClient;
    
    @Test
    public void setTest() throws Exception {
        List<User> users = new ArrayList<User>();
        User user = new User("coco", "coco", "on");     
        User user2 = new User("jack", "jack", "on");
        user.setCreateDate(new Date());
        user2.setCreateDate(new Date());
        users.add(user);
        users.add(user2);
        redisClient.set("users", FastJsonUtils.toJSONStringWithDateFormat(users));
    }
    
    @Test
    public void getTest() throws Exception {
        String json = (String) redisClient.get("users");
        List<User> users = FastJsonUtils.toList(json, User.class);
        for (User record : users) {
            System.err.println(record.getUsername());
        }
    }
}

操作成功。
2.1.2 . 自定義JedisClusterConfig配置類支持Redis集群

步驟:

  • 引入RedisMaven依賴

  • 自定義Redis的集群配置并以實(shí)體類接收

  • 編寫JedisClusterConfig的配置類

  • 使用JedisCluster操作Redis

1. 引入Redis的Maven依賴(省略)
2. 自定義Redis的集群配置并以實(shí)體類接收

config/redis.properties:

# 本地環(huán)境集群
jack.redis.pool.nodes=192.168.5.122:9001,192.168.5.122:9002,192.168.5.122:9003
#redis超時(shí)時(shí)間,單位:秒
jack.redis.pool.timeout=7200
jack.redis.pool.maxAttempts=5
    
@Component
@ConfigurationProperties(prefix = "jack.redis.pool")
@PropertySource("classpath:/config/redis.properties")
public class RedisProperty {

    private String nodes;// redis集群節(jié)點(diǎn)
    private int timeout;// 連接超時(shí)時(shí)間
    private int maxAttempts;// 重連次數(shù)
 
    省略getter();setter();
}

3.  編寫 JedisClusterConfig 的配置類
    
@SpringBootConfiguration
public class JedisClusterConfig {

    @Autowired
    private RedisProperty redisProperty;
    
    @Bean
    public JedisCluster getJedisCluster() {
        String[] redisArray = redisProperty.getNodes().split(",");//獲取服務(wù)器數(shù)組,不考慮空指針問(wèn)題
        Set<HostAndPort> nodes = new HashSet<>();
        for (String ipport : redisArray) {
            String[] ipports = ipport.split(":");
            nodes.add(new HostAndPort(ipports[0].trim(), Integer.valueOf(ipports[1].trim())));
        }
        return new JedisCluster(nodes, redisProperty.getTimeout(), redisProperty.getMaxAttempts());
    }
}

4. 使用配置類中的JedisCluster操作Redis

/**
 * @ClassName: JedisClusterClient
 * @Description:TODO(redis集群的基礎(chǔ)操作工具)
 * @author: wwj
 * @date: 2018年8月27日 下午3:15:22
 */
@Component
public class JedisClusterClient {

    @Autowired
    private JedisCluster jedisCluster;
    @Autowired
    private RedisProperty redisProperty;

    /**
     * 寫入緩存
     * 
     * @param key
     * @param value
     * @return
     */

    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            if (value instanceof String) {
                jedisCluster.set(key, value.toString());
            } else {
                jedisCluster.set(key, FastJsonUtils.toJSONStringWithDateFormat(value));
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 寫入緩存設(shè)置時(shí)效時(shí)間
     * 
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            if (value instanceof String) {
                jedisCluster.setex(key, Integer.valueOf(expireTime + ""), value.toString());
            } else {
                jedisCluster.setex(key, Integer.valueOf(expireTime + ""), FastJsonUtils.toJSONStringWithDateFormat(value));
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 設(shè)置緩存,并且由配置文件指定過(guò)期時(shí)間
     * 
     * @param key
     * @param value
     */
    public void setWithExpireTime(String key, String value) {
        try {
            int expireSeconds = redisProperty.getTimeout();
            set(key, value, Long.valueOf(expireSeconds));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 讀取緩存
     * 
     * @param key
     * @return
     */
    public String get(final String key) {
        return jedisCluster.get(key);
    }

    /**
     * 判斷緩存中是否有對(duì)應(yīng)的value
     * 
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return jedisCluster.exists(key);
    }

    /**
     * 刪除對(duì)應(yīng)的value
     * 
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            jedisCluster.del(key);
        }
    }

    /**
     * 批量刪除對(duì)應(yīng)的value
     * 
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,715評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,290評(píng)論 6 342
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,366評(píng)論 25 708
  • 閑坐品茶與讀書(shū), 靜心修養(yǎng)萬(wàn)事闊。 詩(shī)書(shū)下酒味無(wú)窮, 良辰美景盡其中。 (注,無(wú)押韻,自由體隨意詩(shī)。)
    凡高瀟湘花子閱讀 81評(píng)論 0 1
  • 上帝在創(chuàng)造牛的時(shí)候,對(duì)牛說(shuō)道:“你只能活60年。但要一生為人類干活?!?于是牛放棄了30年的生命,只愿活到30歲。...
    劉鼻涕26閱讀 249評(píng)論 0 0

友情鏈接更多精彩內(nèi)容