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