看过我的文章的都应该有所了解如何使用docker方式进行redis环境的搭建过程,想要了解的可以看下历史文章。今天我们想要分享的就是如何使用redis进行缓存的使用。

缓存,字面含义就是暂时存储,临时存储,其实缓存在整个开发过程中用的很普遍的,其身影随处可见,比如我们Integer类的实现就存在缓存一说,-128~127之间的小数字进行缓存,理解缓存我们必须要知道其含义,好了,关于缓存的相关其它知识,自己后面应该还是会输出对应的文章的。

由于本篇文章的主旋律,也就是本篇文章的主角还是围绕着如何使用redis的本质来进行的,所以我们开始我们的示例程序咯。

在看下面的内容之前我们还是看下百度百科关于redis的介绍。

Redis(全称:Remote Dictionary Server 远程字典服务)是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

首先我们进行看下pom文件的配置内容。

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wpw</groupId>
    <artifactId>springboot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-redis</name>
    <description>Demo project for Spring Boot</description>


    <properties>
        <java.version>1.8</java.version>
    </properties>


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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

然后我们在我们项目的resource文件夹下进行redis连接redis服务器的信息的配置。

##redis数据库索引,一般默认为0
spring.redis.database=0
##redis数据库的服务器地址
spring.redis.host=自己的redisServer服务器地址
##redis数据的服务器连接端口
spring.redis.port=6379
##连接池最大连接数,使用负值表示没有限制
spring.redis.jedis.pool.max-active=8
##连接池最大阻塞等待时间,使用负值表示没有限制
spring.redis.jedis.pool.max-wait=-1ms
##连接池最大的空闲连接
spring.redis.jedis.pool.max-idle=8
##连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0

接下来我们配置信息配置好了之后,就需要进行一些数据准备了,首先我们定义一个实体类,实现序列化接口,这个实现序列化接口一般都是要写上的,因为通过网络传输。

package com.wpw.springbootredis;


import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;


import java.io.Serializable;


@Data
@Builder
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
}

上面我们通过lombok第三方库的形式简写了我们需要的set/get方法的编写,不熟悉lombok可以看下公众号的历史信息,有篇专门讲解lombok如何使用的。

下面我们继续进行redis信息的配置了。

package com.wpw.springbootredis;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * @author pc
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> 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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }


    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 配置序列化
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));


        return RedisCacheManager.builder(factory)
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }
}

上面的实现主要是解决序列化问题,否则容易导致乱码的产生,好了,我们redis大部分的内容基本上完成了,下面我们写个controller进行验证一下了,由于自己是基于docker的方式进行搭建的redis环境,需要了解的可以看下历史信息进行查找。

package com.wpw.springbootredis;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.time.Duration;
import java.util.Objects;


/**
 * @author pc微信公众号~后端Coder
 */
@Component
public class RedisUtil {
    @Resource
    private   RedisTemplate<String, Object> redisTemplate;
    /**
     * @param key   redis存储的key
     * @param value redis存储的value
     */
    void set(String key, Object value) {
        if (Objects.isNull(key) || Objects.isNull(value)) {
            return;
        }
        redisTemplate.opsForValue().set(key,value,Duration.ofMinutes(2));
    }


    /**
     * @param key redis需要的key
     * @return 查找到的value值
     */
    public Object get(String key) {
        if (Objects.isNull(key)) {
            return null;
        }
        return redisTemplate.opsForValue().get(key);
    }
}

上面是自己定义了一个设置值,获取值的工具方法。

package com.wpw.springbootredis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import java.time.Duration;


/**
 * @author 微信公众号~后端Coder
 */
@RestController
public class UserController {
    private final RedisUtil redisUtil;


    public UserController(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }


    @GetMapping(value = "/hello")
    private String redisSet() {
        redisUtil.set("user", new User().setId(1).setName("backCoder").setAge(1));
        return "redis set success";
    }


}

我们开始启动我们的程序,然后访问下面的地址

http://localhost:8080/hello

就会在页面上返回我们自定义的"redis set success"信息,就说明我们成功搭建好了,其实在这篇文章的重点内容就是如何搭建,因为用法很简单。

然后我们通过下面的命令进行redis Server服务器进行查看信息。

spring boot设置协商缓存_spring boot设置协商缓存

好了,今天需要分享的内容就到这里结束了,喜欢文章的可以关注,转发,分享一下。