Spring Boot (23) Lettuce Redis


Spring Boot除了支持常見的ORM框架外,更是對常用的中間件提供了非常好的封裝,隨着SpringBoot2.x的到來,支持的組件也越來越豐富,也越來越成熟,其中對Redis的支持不僅僅是它豐富的API,更是替換掉了底層Jedis的依賴,取而代之的是Lettuce。

 

Redis

  Redis是一個開源的使用ANSI c語言編寫、支持網絡、可基於內存也可持久化的日執行、key-value數據庫,並提供多種語言的API,相比memcached它支持更多類型存儲(字符串、哈希、集合、有續集合、列表),同時Redis是線程安全的。

 

Lettuce

  Lettuce和Jedis都是連接Redis Server的客戶端程序,Jedis在實現上是直連redis server,多線程環境下非線程安全,除非使用連接池,為每個Jedis勢力增加物理連接。Lettuce基於Netty的勢力連接,可以再多個線程間並發訪問,且線程安全,滿足多線程環境下的並發訪問,同時它是可伸縮的設計,一個連接勢力不夠的情況也可以按需增加連接實例。

 

導入依賴

  在pom.xml中引入spring-boot-starter-data-redis

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

 

屬性配置

  在application.yml中配置如下內容

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/david2018_db?characterEncoding=utf8
    username: root
    password: 1234
  redis:
    host: 10.211.55.5 #redis服務器地址
    timeout: 10000 #超時時間
    database: 0 #0-15 16個庫 默認0
    lettuce:
      pool:
        max-active: 8 #最大連接數
        max-wait: -1 #默認-1 最大連接阻塞等待時間
        max-idle: 8 #最大空閑連接 默認8
        min-idle: 0 #最小空閑連接

實體類

package com.spring.boot.bean;

import java.io.Serializable;

public class User implements Serializable {
    private Integer userId;
    private String userName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

 

自定義Template

  默認情況下的模板只能支持RedisTemplate<String,String>,只能存字符串。這時需要自定義模板,當自定義模板后又想存儲String字符串時,可以使用StringRedisTemplate的方式,他們倆並不沖突。

package com.spring.boot.utils;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {

    @Bean
    public RedisTemplate<String,Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Serializable> template = new RedisTemplate<String,Serializable>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

測試redis

    @GetMapping("/redis")
    public String redis(){
        //字符串
        stringRedisTemplate.opsForValue().set("rediskey","redisvalue");
        String rediskey = stringRedisTemplate.opsForValue().get("rediskey");
        System.out.println(rediskey);
        //對象
        User user = new User(1,"username");
        redisCacheTemplate.opsForValue().set("user",user);

        User getUser = (User) redisCacheTemplate.opsForValue().get("user");
        System.out.println(getUser.getUserName());
        return "redis";
    }

 

下列就是redis其他類型的對應操作方式:

  opsForValue:對應String字符串

  opsForZSet:對應ZSet有序集合

  opsForHash:對應Hash哈希

  opsForList:對應List列表

  opsForSet:對應Set集合

  opsForGeo:對應GEO地理位置

 


免責聲明!

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



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