Spring中使用redis


參考博客

https://blog.csdn.net/winter_chen001/article/details/80614331

1.創建一個Maven項目

2.導入SpringBoot和Redis需要的依賴

 

<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.jtfr</groupId>
  <artifactId>SpringBootChapter1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  
    <!--版本采用的是最新的 2.0.1.RELEASE 開發中請記得版本一定要選擇 RELEASE -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> 
    </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>
        <!-- web導入 -->
        <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 編譯插件,用於打jar包使用 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.配置文件配置redis和連接池的信息

spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=root #根據需要
# 連接超時時間(毫秒)
spring.redis.timeout=10000
# Redis默認情況下有16個分片,這里配置具體使用的分片,默認是0
spring.redis.database=0
# 連接池最大連接數(使用負值表示沒有限制) 默認 8
spring.redis.lettuce.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
spring.redis.lettuce.pool.max-wait=-1
# 連接池中的最大空閑連接 默認 8
spring.redis.lettuce.pool.max-idle=8
# 連接池中的最小空閑連接 默認 0
spring.redis.lettuce.pool.min-idle=0

3.編寫Springboot啟動類

package com.winterchen;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 啟動類必須要有,Test才能啟動。
 * @author ckm
 *
 */
@SpringBootApplication
public class App {
    
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

4.編寫測試用的實體類

package com.winterchen.entity;

import java.io.Serializable;

/**
 * 測試對象實體類
 */
public class User implements Serializable{
    private static final long serialVersionUID = 8655851615465363473L;
    private Long id;
    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}

5.RedisTemplate的配置

package com.winterchen.config;

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;

/**
 * RedisTemplate的配置
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {


    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        // 設置 key 序列化方式,StringRedisSerializer的序列化方式,如果沒有設置,key前面會有一段字節。
        template.setKeySerializer(new StringRedisSerializer());
        // 設置 value 序列化方式,序列化為 json。
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 設置連接池
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

6.測試類編寫

package com.winterchen;

import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import com.winterchen.entity.User;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootLettuceRedisApplicationTests {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpringBootLettuceRedisApplicationTests.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 測試線程安全
     */
    @Test
    public void testSafe() {
        // 測試線程安全, 每次都是增加 1000 說明在多線程的時候 redis還是安全的。注意:這里不一定開了1000個線程,全看執行速度怎么樣。
        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        stringRedisTemplate.opsForValue().set("k0", "0");
        for (int i = 0; i < 1000; i++) {
            stringRedisTemplate.opsForValue().increment("k0", 1);
        }
        final String k0 = stringRedisTemplate.opsForValue().get("k0");
        LOGGER.info("[線程安全結果] - [{}]", k0);
    }

    @Test
    public void setAndGet() {
        stringRedisTemplate.opsForValue().set("k1", "v1");
        final String k1 = stringRedisTemplate.opsForValue().get("k1");
        LOGGER.info("[字符緩存結果] - [{}]", k1);
        stringRedisTemplate.opsForValue().set("k2", "v2中文");
        final String k2 = stringRedisTemplate.opsForValue().get("k2");
        LOGGER.info("[字符緩存中文結果] - [{}]", k2);
        // TODO 以下只演示整合,具體Redis命令可以參考官方文檔,Spring Data Redis 只是改了個名字而已,Redis支持的命令它都支持
        String key = "battcn:user:1";
        redisTemplate.opsForValue().set(key, new User(1L, "u1中文", "pa"));
        // TODO 對應 String(字符串)
        final User user = (User) redisTemplate.opsForValue().get(key);
        LOGGER.info("[對象緩存結果] - [{}]", user);
    }
    
    /**
     * 設置超時測試
     */
    @Test
    public void testSetAndTimeOut() {
        // 設置超時時間
        stringRedisTemplate.opsForValue().set("testTimeOut", "100", 3,TimeUnit.SECONDS);
        LOGGER.info("[查詢結果] - [{}]", stringRedisTemplate.opsForValue().get("testTimeOut"));
        // 休眠 5 秒后,就超時了,查詢不到了。
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }
        LOGGER.info("[休眠五秒查詢結果] - [{}]", stringRedisTemplate.opsForValue().get("testTimeOut"));
    }
    
    /**
     * 移除數據測試
     */
    @Test
    public void testRemove() {
        redisTemplate.opsForValue().set("removetest", "有數據");
        LOGGER.info("[查詢結果] - [{}]", stringRedisTemplate.opsForValue().get("removetest"));
        redisTemplate.delete("removetest");
        LOGGER.info("[刪除 key 后查詢結果] - [{}]", stringRedisTemplate.opsForValue().get("removetest"));
    }
    
}

7.執行結果

 


免責聲明!

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



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