1. 程式人生 > >SpringBoot之Redis的支援

SpringBoot之Redis的支援

一、簡介
redis是一個key-value儲存系統。和Memcached類似,它支援儲存的value型別相對更多,包括string(字串)、list(連結串列)、set(集合)、zset(sorted set –有序集合)和hash(雜湊型別)。這些資料型別都支援push/pop、add/remove及取交集並集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎上,redis支援各種不同方式的排序。與memcached一樣,為了保證效率,資料都是快取在記憶體中。區別的是redis會週期性的把更新的資料寫入磁碟或者把修改操作寫入追加的記錄檔案,並且在此基礎上實現了master-slave(主從)同步。

Redis 是一個高效能的key-value資料庫。 redis的出現,很大程度補償了memcached這類key/value儲存的不足,在部 分場合可以對關係資料庫起到很好的補充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客戶端,使用很方便。

二、Spring的支援
(1)配置
Spring對Redis的支援也是通過Spring Data Redis來實現的,Spring Data JPA為我們提供了連線相關的ConnectionFactory和資料操作相關的RedisTemplate。在此特別指出,Spring Data Redis只對Redis 2.6和2.8版本做過測試。
根據Redis的不同的Java客戶端,Spring Data Redis提供瞭如下的ConnectionFactory:
JedisConnectionFactory:使用Jedis作為Redis客戶端。
JredisConnectionFactory:使用Jredis作為Redis客戶端。
LettuceConnectionFactory:使用Lettuce作為Redis客戶端。
SrpConnectionFactory:使用Spullara/redis-protocol作為Redis客戶端。
配置方式如下:

@Bean
public RedisConnectionFactory redisConnectionFactory() {
    return new JedisConnectionFactory();
}

RedisTemplate配置方式如下:

@Bean
public RedisTemplate<Object, Object> redisTemplate()throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object
>(); template.setConnectionFactory(redisConnectionFactory()); return template; }

(2)使用
Spring Data Redis為我們提供了RedisTemplate和StringRedisTemplate兩個模板來進行資料操作,其中,StringRedisTemplate只針對鍵值都是字元型的資料進行操作。
RedisTemplate和StringRedisTemplate提供的主要資料訪問方法如圖:
這裡寫圖片描述
更多關於Spring Data Redis的操作,請檢視SpringData Redis官方文件。

(3)定義Serializer
當我們的資料儲存到Redis的時候,我們的鍵(key)和值(value)都是通過Spring提供的Serializer序列化到資料庫的。RedisTemplate預設使用的是JdkSerializationRedisSerializer,StringRedisTemplate預設使用的是StringRedisSerializer。
Spring Data JPA為我們提供了下面的Serializer:
GenericToStringSerializer、
Jackson2JsonRedisSerializer、
JacksonJsonRedisSerializer、
JdkSerializationRedisSerializer、OxmSerializer、
StringRedisSerializer。

三、SpringBoot的支援
Spring Boot對Redis的支援,org.springframework.boot.autoconfigure.dao.redis包:
這裡寫圖片描述

RedisProperties向我們展示了可以使用以“spring.redis”為字首的屬性在application.properties中配置Redis,主要屬性如下:

# REDIS (RedisProperties)
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:[email protected]:6379
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.ssl=false # Enable SSL support.
spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0 # Connection timeout in milliseconds.

四、實戰
(1)安裝Redis
非Docker安裝。若不基於Docker安裝的話,我們可以到http://redis.io/download下載合適版本的Redis。
(2)工具,RedisDesktopManager
(3)pom.xml

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

(4)Red模型類

public class Red implements Serializable{
    private static final long serialVersionUID = 1L;
    private String id;
    private String name;
    private Integer age;
    public Red(){
        super();
    }

    public Red(String id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //省略get、set
}

(5)資料訪問RedDao

@Repository
public class RedDao {
    @Autowired
    StringRedisTemplate stringRedisTemplate; //1Spring Boot已為我們配置StringRedisTemplate,在此處可以直接注入。
    @Resource(name = "stringRedisTemplate")
    ValueOperations<String, String> valOpsStr; //3可以使用@Resource註解指定stringRedisTemplate,可注入基於字串的簡單屬性操作方法。
    @Autowired
    RedisTemplate<Object, Object> redisTemplate; //2Spring Boot已為我們配置RedisTemplate,在此處可以直接注入。

    @Resource(name = "redisTemplate")
    ValueOperations<Object, Object> valOps; //4可以使用@Resource註解指定redisTemplate,可注入基於物件的簡單屬性操作方法;

    public void stringRedisTemplateDemo() { //5通過set方法,儲存字串型別。
        valOpsStr.set("xx", "yy");
    }

    public void save(Red person) {
        valOps.set(person.getId(), person); //6通過set方法,儲存物件型別。

    }

    public String getString() {
        return valOpsStr.get("xx");//7通過get方法,獲得字串。
    }

    public Red getRed() {
        return (Red) valOps.get("1");//8通過get方法,獲得物件。
    }
}

(6)配置Redis,在啟動類中

public class SpringbootcacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootcacheApplication.class, args);
    }

    @Bean
    @SuppressWarnings({"rawtypes", "unchecked"})
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>
                ();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer); //1設定值(value)的序列化採用Jackson2JsonRedisSerializer。
        template.setKeySerializer(new StringRedisSerializer()); //2設定鍵(key)的序列化採用StringRedisSerializer。
        template.afterPropertiesSet();
        return template;
    }
}

(7)控制器RedController

@RestController
@RequestMapping("/redis")
public class RedController {
    @Autowired
    RedDao redDao;

    @RequestMapping("/set") //1演示設定字元及物件。
    public void set() {
        Red red = new Red("1", "aaa", 16);
        Red red2 = new Red("2", "bbb", 17);
        Red red3 = new Red("3", "ccc", 18);
        Red red4 = new Red("4", "ddd", 19);
        Red red5 = new Red("5", "eee", 20);
        redDao.save(red);
        redDao.save(red2);
        redDao.save(red3);
        redDao.save(red4);
        redDao.save(red5);
        redDao.stringRedisTemplateDemo();
    }

    @RequestMapping("/getStr") //2演示獲得字元。
    public String getStr() {
        return redDao.getString();
    }

    @RequestMapping("/getRed") //3演示獲得物件。
    public Red getPerson() {
        return redDao.getRed();
    }
}

以上是關於在SpringBoot中使用redis的例子。

參考資料《JavaEE開發的顛覆者 Spring Boot》

新手一枚,歡迎拍磚~ ~ ~

相關推薦

SpringBootRedis支援

一、簡介 redis是一個key-value儲存系統。和Memcached類似,它支援儲存的value型別相對更多,包括string(字串)、list(連結串列)、set(集合)、zset(sorted set –有序集合)和hash(雜湊型別)。這些資料型別

19-SpringBootRedis(六)——Redis快取實現

SpringBoot之Redis(六)——Redis快取實現 1. 新增maven依賴 2. 引數配置 3. 實體類 4. Dao 5. Service 6. Controller 7. 原始碼下載 1. 新增m

18-SpringBootRedis(五)——使用Lua 指令碼

SpringBoot之Redis(五)——使用Lua 指令碼 1. 簡易Lua 指令碼 2. 帶有引數的Lua 3. 原始碼下載 在Redis中有兩種執行Lua的方法, 一種是直接傳送Lua到Redis伺服器去執行,另一種是先把Lua

17-SpringBootRedis(四)——Redis流水線

SpringBoot之Redis(四)——Redis流水線 在預設的情況下, Redis 客戶端是一條條命令傳送給Redis 伺服器的,這樣顯然效能不高。在關係資料庫中我們可以使用批量,也就是隻有需要執行SQL 時,才一次性地傳送所有的SQL 去執行,這樣效能就提高了許多

16-SpringBootRedis(三)——Redis事務機制

SpringBoot之Redis(三)——Redis事務機制 1. Redis 事務執行過程 2. 開啟事務支援 3. 測試 4. 測試結果說明 5. 原始碼下載 1. Redis 事務執行過程 Redis 事務執行過程

15-SpringBootRedis(二)——Redis Cluster

SpringBoot之Redis(二)——Redis Cluster 與整合單機Redis相比,SpringBoot整合Redis Cluster只需修改application.yml配置檔案如下: spring: redis: cluster:

14-SpringBootRedis(一)——單機Redis

SpringBoot之Redis(一)——單機Redis 1. pom.xml 2. application.yml 3. Redis序列化配置類 4. 案例演示 4.1 redis操作字串 4.2 redis操作雜湊資料

springbootredis的配置

當看這邊文章之前,相信大家對redis已經能夠熟悉的運用,對springmvc也有一定的瞭解了。redis,在個人的觀點中是一個很優秀的快取組建,無論是單用,還是做叢集用,輕便,簡單,持久,都很不錯。言歸正傳,看下錶題,這裡講一下springboot配置redis是如何實現

java鬼混筆記:springbootredis儲存物件

首先加入springboot-redis依賴:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-da

SpringBoot初始教程Redis集中式Session管理

ont ttr imp exce sna tap user gap col 1.介紹 有關Session的管理方式這裏就不再進行討論,目前無非就是三種單機Session(基於單機內存,無法部署多臺機器)、基於Cookie(安全性差)、基於全局的統一Session管理(red

資料新增非同步解析重新整理大資料量redis (——)(二) SpringBootCommandLineRunner介面和ApplicationRunner介面

在spring boot應用中,我們可以在程式啟動之前執行任何任務。為了達到這個目的,我們需要使用CommandLineRunner或ApplicationRunner介面建立bean,spring boot會自動監測到它們。這兩個介面都有一個run()方法,在實現介面時需要覆蓋該方法,並使用@

1101-springboot使用redistemplate優雅地操作redis

springboot之使用redistemplate優雅地操作redis 概述 本文內容主要 關於spring-redis 關於redis的key設計 redis的基本資料結構 介紹redis與springboot的整合 sringboot中的rediste

PHP 擴充套件支援 redis

       在很多企業中,不管是 LNMP 架構,還是 LAMP 架構,都會通過redis做資料快取,而主要因素就是,redis 對資料的存取都是在記憶體中進行,因此,對資料的處理速度相對硬碟來說,快樂佈置一個數量級,今天,我們就來講一下關閉 php r

SpringBoot初始教程Redis集中式Session管理(四)

SpringBoot初始教程之Redis集中式Session管理(四) 1.介紹 有關Session的管理方式這裡就不再進行討論,目前無非就是三種單機Session(基於單機記憶體,無法部署多臺機器)、基於Cookie(安全性差)、基於全域性的統一Session管理(redis、mysql)

深入理解Redis系列SpringBoot整合Redis

SpringBoot環境 快速搭建一個SpringBoot工程 進入 https://start.spring.io 網站, 使用該網站初始化一個SpringBoot工程 新增相關依賴 因為使用spring initializer已經幫我們把Redis的依賴建立好了; 但是

SpringBoot 快取redis

專案目錄結構 依賴包引入   <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="htt

Springboot使用Redis做快取資料

一、新增Redis依賴 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o

springboot番外redis

目錄 redis連線工廠類  template(模版) key和value序列化 springboot快取某個方法 申明快取管理器 新增快取 刪除快取 自定義ke

SpringBoot整合redis實現快取

主要程式碼: String key = "teacher_"+id; boolean hasKey = redisTemplate.hasKey(key); ValueOperations<String,Teacher> o

SpringBoot整合Redis進階篇

上一篇文章寫了SpringBoot和Redis的基本操作(SpringBoot整合Redis之入門篇)。這些都是小打小鬧,本篇文章我們來一些進階的操作。主要講解一下SpringBoot中使用Redis的基本操作類,實現Redis的整合。Redis的基本操作類就是已經封裝好的C