国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

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

發(fā)布時(shí)間:2021-07-17 21:51 來(lái)源:腳本之家 閱讀:0 作者:Apollo的小太陽(yáng) 欄目: 編程語(yǔ)言 歡迎投稿:712375056

程序結構:

一、配置

 1. 在pom.xml中添加依賴(lài)

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應用基本環(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數據索引(默認為0)
    database: 0
    # Redis服務(wù)器地址
    host: 127.0.0.1
    # Redis服務(wù)器連接端口
    port: 6379
#     Redis服務(wù)器連接密碼(默認為空)
#    password: 123456

3. 通過(guò)配置類(lèi),設置redis

RedisConfig類(lèi)如下:

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對象,將會(huì )替代默認的SESSION序列化對象。
     * 默認是JdkSerializationRedisSerializer,缺點(diǎn)是需要類(lèi)實(shí)現Serializable接口。
     * 并且在反序列化時(shí)如果異常會(huì )拋出SerializationException異常,
     * 而SessionRepositoryFilter又沒(méi)有處理異常,故如果序列化異常時(shí)就會(huì )導致請求異常
     */
    @Bean(name = "springSessionDefaultRedisSerializer")
    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
 
    /**
     * JacksonJsonRedisSerializer和GenericJackson2JsonRedisSerializer的區別:
     * GenericJackson2JsonRedisSerializer在json中加入@class屬性,類(lèi)的全路徑包名,方便反系列化。
     * JacksonJsonRedisSerializer如果存放了List則在反系列化的時(shí)候,
     * 如果沒(méi)指定TypeReference則會(huì )報錯java.util.LinkedHashMap cannot be cast。
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
 
        // 使用Jackson2JsonRedisSerialize 替換默認序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                            new Jackson2JsonRedisSerializer(Object.class);
 
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 設置value的序列化規則和 key的序列化規則
        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. 實(shí)體類(lèi)

實(shí)體類(lèi)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. 公共返回類(lèi)

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;
    }
 
    //這個(gè)方法和Builder設計模式二選一即可,功能是重復的
    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)內部類(lèi),這里使用Builder設計模式
    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方法,這里的方法一定不能少,否則返回時(shí)無(wú)法將對象序列化
}

4. 請求處理Controller

RedisController類(lèi)如下:

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中添加數據
     * @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中獲取數據
     * @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方法是必須的,否則會(huì )報錯:HttpMessageNotWritableException: No converter found for return value of type: class com.apollo.common.ApiResult,找不到ApiResult類(lèi)型的轉換器。

三、測試

1. 測試添加

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

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

登錄到redis,使用命令dbsize查看存儲的數據量:

數據量為3,對應我們上邊程序中的3步操作。

2. 測試獲取

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

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

與我們之前存入的數據對比,是正確的。

四、代碼地址

github地址:

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

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

中文字幕在线观看2o18| 又粗又猛又黄又爽无遮挡| 久久综合久久综合九色| 狠狠亚洲婷婷综合色香五月加勒比| 国产伦精品一区二区三区妓女| 亚洲AV日韩AV鸥美在线观看|