首页 > 数据库 >springboot整合redis详解

springboot整合redis详解

时间:2022-11-20 11:13:27浏览次数:34  
标签:springboot boot redis springframework 详解 import org data

springboot整合redis

1.首先创建springboot工程

2.配置pom.xml文件

<?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>
    <groupId>com.atguigu</groupId>
    <artifactId>redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.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-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.atguigu.redis.RedisApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3.配置 application.yaml文件

spring:
  redis:
    host: host
    port: port
    password: password
    database: 0
#换成你自己的配置


4.配置redis的配置类

package com.atguigu.redis.config;

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;

import java.time.Duration;

@EnableCaching //开启缓存
@Configuration  //配置类
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.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 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);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}


5.测试连接

package com.atguigu.redis.controller;

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

/**
 * @PROJECT_NAME: redis
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/11/20 10:48
 */
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public String  testRedis(){
        //设置值到redis里面去
        redisTemplate.opsForValue().set("name","lucy");
        //获取值
         String name = (String) redisTemplate.opsForValue().get("name");
         return name;
    }


}

6.浏览器验证结果

标签:springboot,boot,redis,springframework,详解,import,org,data
From: https://www.cnblogs.com/wiseleer/p/16908044.html

相关文章

  • 性能监控命令vmstat详解【杭州多测师】【杭州多测师_王sir】
    vmstat命令:用来获得有关进程、虚存、页面交换空间及CPU活动的信息。这些信息反映了系统的负载情况。vmstat 命令的输出vmstat 1 10  实例解读一:​​​​​CPU状态的监......
  • 性能监控命令top详解【杭州多测师】【杭州多测师_王sir】
     一、top命令介绍top命令是Linux系统中常用的性能分析工具,可以实时地查看系统的运行情况,比如内存、CPU、负载以及各个进程的资源占用情况二、top命令详解第一行:top-14:39......
  • Redis学习(六)之redis中的数据类型之SortedSet类型
      1、sortedset中每个元素有一个浮点值。 2、浮点值越大的,元素排序就大,浮点值相同,则按元素的字符串值比较。 3、元素必须唯一。  1、ZADDkey[NX|XX][GT......
  • 开发笔记1.2-Redis的配置和使用
    1.下载Redis的安装包首先需要去官网下载redis的安装包下载地址:https://redis.io/download/2.安装预备工作2.1创建对应目录和放置文件到指定目录#新建/usr/loca......
  • unix网络编程1.1——TCP协议详解(一)
    目录前言网络7层协议与4层协议TCP/IP四层模型通信过程TCP与UDP的区别:TCP:UDP:CS模型-TCP总览数据进入协议栈时的封装过程TCP数据格式TCP三次握手通信时序图TCP四次挥手半关......
  • git checkout 命令图文详解
    目录gitcheckoutbranchname(切换本地分支)切换远程分支放弃修改gitcheckout.gitcheckout–filenamegitcheckout-f回退版本检出文件,分支转换。gitcheckoutbran......
  • Pod控制器详解(ReplicaSet)
    Pod控制器详解Pod控制器介绍Pod是kubernetes的最小管理单元,在kubernetes中,按照pod的创建方式可以将其分为两类:-自主式pod:kubernetes直接创建出来的Pod,这种pod删除后就......
  • python ddddocr图片验证码详解
     下载地址:https://pypi.tuna.tsinghua.edu.cn/simple/ddddocr/安装命令:pipinstallD:\ChromeCoreDownloads\ddddocr-1.3.0-py3-none-any.whl-ihttps://pypi.tuna.ts......
  • SpringBoot13(springboot自定义Starter)
    实现:一、自定义Starter最简实现1、classpath(springboot下是resources)路径下创建MATA-INF/spring.factories文件,写入需要加载的......
  • super详解
    Super详解super注意点:1.super调用父类的构造方法,必须在构造方法的第一个!2.super必须只能出现在子类的方法或者构造方法中!3.super和this不能同时调用构造方法!vs.t......