最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Springboot項目中使用redis的配置詳解

 更新時間:2021年04月27日 10:17:44   作者:Apollo的小太陽  
這篇文章主要介紹了Springboot項目中使用redis的配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

程序結(jié)構(gòu):

一、配置

 1. 在pom.xml中添加依賴

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.lyy</groupId>
    <artifactId>redis-test</artifactId>
    <version>0.1-SNAPSHOT</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <!--始終從倉庫中獲取-->
        <!--<relativePath/>-->
    </parent>
 
    <dependencies>
        <!--web應(yīng)用基本環(huán)境,如mvc-->
        <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>
    </dependencies>
</project>

其中,spring-boot-starter-web包含springmvc。

2. 配置application.yml

application.yml文件如下:

server:
  port: 11011
  servlet:
    context-path: /api/v1
 
spring:
  redis:
    # Redis數(shù)據(jù)庫索引(默認(rèn)為0)
    database: 0
    # Redis服務(wù)器地址
    host: 127.0.0.1
    # Redis服務(wù)器連接端口
    port: 6379
#     Redis服務(wù)器連接密碼(默認(rèn)為空)
#    password: 123456

3. 通過配置類,設(shè)置redis

RedisConfig類如下:

package com.apollo.config;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
@Configuration
@EnableCaching
public class RedisConfig {
 
    @Autowired
    private ObjectMapper objectMapper;
 
    /**
     * 自定義springSessionDefaultRedisSerializer對象,將會替代默認(rèn)的SESSION序列化對象。
     * 默認(rèn)是JdkSerializationRedisSerializer,缺點是需要類實現(xiàn)Serializable接口。
     * 并且在反序列化時如果異常會拋出SerializationException異常,
     * 而SessionRepositoryFilter又沒有處理異常,故如果序列化異常時就會導(dǎo)致請求異常
     */
    @Bean(name = "springSessionDefaultRedisSerializer")
    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
 
    /**
     * JacksonJsonRedisSerializer和GenericJackson2JsonRedisSerializer的區(qū)別:
     * GenericJackson2JsonRedisSerializer在json中加入@class屬性,類的全路徑包名,方便反系列化。
     * JacksonJsonRedisSerializer如果存放了List則在反系列化的時候,
     * 如果沒指定TypeReference則會報錯java.util.LinkedHashMap cannot be cast。
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
 
        // 使用Jackson2JsonRedisSerialize 替換默認(rèn)序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                            new Jackson2JsonRedisSerializer(Object.class);
 
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 設(shè)置value的序列化規(guī)則和 key的序列化規(guī)則
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
 
        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
 
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

二、邏輯代碼

1. 程序入口

package com.apollo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
@SpringBootApplication
public class Application  {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2. 實體類

實體類Animal如下:

package com.apollo.bean;
 
/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
public class Animal {
    private Integer weight;
    private Integer height;
    private String name;
 
    public Animal(Integer weight, Integer height, String name) {
        this.weight = weight;
        this.height = height;
        this.name = name;
    }
 
    ……這里是get、set方法
}

3. 公共返回類

package com.apollo.common;
 
/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
public class ApiResult {
    public static final Integer STATUS_SUCCESS = 0;
    public static final Integer STATUS_FAILURE = -1;
 
    public static final String DESC_SUCCESS = "操作成功";
    public static final String DESC_FAILURE = "操作失敗";
 
    private Integer status;
    private String desc;
    private Object result;
 
    private ApiResult() {}
 
    private ApiResult(Integer status, String desc, Object result) {
        this.status = status;
        this.desc = desc;
        this.result = result;
    }
 
    //這個方法和Builder設(shè)計模式二選一即可,功能是重復(fù)的
    public static ApiResult success(Object result) {
        return success(DESC_SUCCESS, result);
    }
 
    //同上
    public static ApiResult success(String desc, Object result) {
        return new ApiResult(STATUS_SUCCESS, desc, result);
    }
 
    //同上
    public static ApiResult failure(Integer status) {
        return failure(status, null);
    }
 
    //同上
    public static ApiResult failure(Integer status, String desc) {
        return failure(status, desc, null);
    }
 
    //同上
    public static ApiResult failure(Integer status, String desc, Object result) {
        return new ApiResult(status, desc, result);
    }
 
    public static Builder builder() {
        return new Builder();
    }
 
    //靜態(tài)內(nèi)部類,這里使用Builder設(shè)計模式
    public static class Builder {
        private Integer status;
        private String desc;
        private Object result;
 
        public Builder status(Integer status) {
            this.status = status;
            return this;
        }
 
        public Builder desc(String desc) {
            this.desc = desc;
            return this;
        }
 
        public Builder result(Object result) {
            this.result = result;
            return this;
        }
 
        public ApiResult build() {
            return new ApiResult(status, desc, result);
        }
    }
 
    ……這里是get、set方法,這里的方法一定不能少,否則返回時無法將對象序列化
}

4. 請求處理Controller

RedisController類如下:

package com.apollo.controller;
 
import com.apollo.bean.Animal;
import com.apollo.common.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author :apollo
 * @since :Created in 2019/2/22
 */
@RestController
@RequestMapping(value = "/redis")
public class RedisController {
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    /**
     * 測試向redis中添加數(shù)據(jù)
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    public ApiResult addData2Redis(@PathVariable("id") Integer id) {
 
        redisTemplate.opsForValue().set("first", id);
        redisTemplate.opsForValue().set("second", "hello world");
        redisTemplate.opsForValue().set("third",
                new Animal(100, 200, "二狗子"));
 
        return ApiResult.builder()
                        .status(ApiResult.STATUS_SUCCESS)
                        .desc("添加成功")
                        .build();
    }
 
    /**
     * 測試從redis中獲取數(shù)據(jù)
     * @return
     */
    @GetMapping("/redis-data")
    public ApiResult getRedisData() {
        Map<String, Object> result = new HashMap<>();
        result.put("first", redisTemplate.opsForValue().get("first"));
        result.put("second", redisTemplate.opsForValue().get("second"));
        result.put("third", redisTemplate.opsForValue().get("third"));
 
        return ApiResult.builder()
                .status(ApiResult.STATUS_SUCCESS)
                .desc("獲取成功")
                .result(result)
                .build();
    }
}

注意:這里是返回ApiResult對象,需要將返回的對象序列化,所以ApiResult中的get/set方法是必須的,否則會報錯:HttpMessageNotWritableException: No converter found for return value of type: class com.apollo.common.ApiResult,找不到ApiResult類型的轉(zhuǎn)換器。

三、測試

1. 測試添加

使用postman請求http://localhost:11011/api/v1/redis/5,返回結(jié)果:

{
    "status": 0,
    "desc": "添加成功",
    "result": null
}

登錄到redis,使用命令dbsize查看存儲的數(shù)據(jù)量:

數(shù)據(jù)量為3,對應(yīng)我們上邊程序中的3步操作。

2. 測試獲取

使用postman請求http://localhost:11011/api/v1/redis/redis-data,返回結(jié)果:

{
    "status": 0,
    "desc": "獲取成功",
    "result": {
        "third": {
            "weight": 100,
            "height": 200,
            "name": "二狗子"
        },
        "first": 5,
        "second": "hello world"
    }
}

與我們之前存入的數(shù)據(jù)對比,是正確的。

四、代碼地址

github地址:https://github.com/myturn0/redis-test.git

到此這篇關(guān)于Springboot項目中使用redis的配置詳解的文章就介紹到這了,更多相關(guān)Springboot redis配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于springboot與axios的整合問題

    基于springboot與axios的整合問題

    這篇文章主要介紹了springboot與axios的整合問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Spring boot webService使用方法解析

    Spring boot webService使用方法解析

    這篇文章主要介紹了Spring boot webService使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-09-09
  • Java面向?qū)ο蟮姆庋b你了解嗎

    Java面向?qū)ο蟮姆庋b你了解嗎

    這篇文章主要為大家詳細(xì)介紹了Java面向?qū)ο蟮姆庋b,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • mybatis中mapper代理的生成過程全面分析

    mybatis中mapper代理的生成過程全面分析

    這篇文章主要為大家介紹了mybatis中mapper代理的生成過程全面分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • SpringBoot 關(guān)于Feign的超時時間配置操作

    SpringBoot 關(guān)于Feign的超時時間配置操作

    這篇文章主要介紹了SpringBoot 關(guān)于Feign的超時時間配置操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java基礎(chǔ)之位運算知識總結(jié)

    Java基礎(chǔ)之位運算知識總結(jié)

    最近接觸到了java位運算,之前對位運算的了解僅僅停留在表現(xiàn)結(jié)果上,乘2除以2,對背后的原理并不了解,現(xiàn)在學(xué)習(xí)記錄一下,需要的朋友可以參考下
    2021-05-05
  • Java中Future、FutureTask原理以及與線程池的搭配使用

    Java中Future、FutureTask原理以及與線程池的搭配使用

    這篇文章主要為大家詳細(xì)介紹了Java中Future、FutureTask原理以及與線程池的搭配使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-09-09
  • java打jar包與找不到依賴包的問題

    java打jar包與找不到依賴包的問題

    這篇文章主要介紹了java打jar包與找不到依賴包的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • JAVA文件讀寫例題實現(xiàn)過程解析

    JAVA文件讀寫例題實現(xiàn)過程解析

    這篇文章主要介紹了JAVA文件讀寫例題實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • maven本地有包但是引不進(jìn)來的解決方案

    maven本地有包但是引不進(jìn)來的解決方案

    如果Maven本地存在需要的包,但無法引入,可以通過檢查項目的pom.xml文件、確保項目在Maven中正確構(gòu)建、清除Maven本地緩存或刪除整個本地倉庫等方法解決,務(wù)必確認(rèn)本地倉庫中確實存在該包,并且依賴項配置正確
    2024-09-09

最新評論

南华县| 承德县| 河间市| 如皋市| 云林县| 电白县| 兴和县| 玉门市| 望奎县| 南昌县| 潢川县| 日土县| 贺州市| 兴隆县| 文水县| 兴化市| 克山县| 汝城县| 韶关市| 麻江县| 秦皇岛市| 陆丰市| 永靖县| 北安市| 五常市| 福建省| 洛阳市| 海丰县| 尉氏县| 夏河县| 苍溪县| 新化县| 文登市| 西宁市| 荥经县| 泽州县| 英吉沙县| 屏边| 莫力| 灌阳县| 达州市|