SprinBoot2.x 整合 Redis

【简介】

SpringBoot2.x 整合 Redis 的 demo,并没有整合数据库和mybatis等


【本文 Demo】

https://github.com/qidasheng2012/springboot2.x_redis/tree/branch-redis


【项目结构】

SprinBoot2.x 整合 Redis_第1张图片


【pom.xml】


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.0.RELEASEversion>
        <relativePath/> 
    parent>

    <groupId>com.examplegroupId>
    <artifactId>springboot2.x_redisartifactId>
    <version>1.0.0version>
    <name>springboot2.x_redisname>
    <description>SpringBoot2.x demo project for Redisdescription>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-pool2artifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
    dependencies>

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

project>

【application.yml】

server:
  port: 80

spring:
  redis:
    #数据库索引
    database: 0
    host: 127.0.0.1
    port: 6379
    password: root
    lettuce:
      pool:
        #最大连接数
        max-active: 8
        #最大阻塞等待时间(负数表示没限制)
        max-wait: -1
        #最大空闲
        max-idle: 8
        #最小空闲
        min-idle: 0
        #连接超时时间
        timeout: 10000


【RedisConfig】

主要解决redis序列化的问题,不然存对象会乱码

package com.example.springboot_redis.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;

/**
 * Redis的配置类
 *
 * @author qp
 * @date 2019/7/19 9:46
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        
        return redisTemplate;
    }

}

【User 】

测试实体类

推荐使用lombok的@Data注解,简化实体类get set方法,最优雅的是使用@builder注解
Lombok【汇总】

package com.example.springboot_redis.domain;

import lombok.Data;

import java.io.Serializable;

/**
 * @author qp
 * @date 2019/7/19 9:47
 */
@Data
public class User implements Serializable {
    // 主键
    private Integer id;
    // 用户code
    private String userCode;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
}

【UserController 】

测试Redis的controller

package com.example.springboot_redis.contoller;

import com.example.springboot_redis.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * 测试Redis的controller
 *
 * @author qp
 * @date 2019/7/19 9:50
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    // 获取字符串
    @GetMapping("/get/{key}")
    public String getRedis(@PathVariable(name = "key") String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    // 保存字符串
    @PostMapping("/set/{key}/{value}")
    public String getRedis(@PathVariable(name = "key") String key, @PathVariable(name = "value") String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        return "SUCCESS";
    }

    // 保存对象
    @PostMapping("/postEntity")
    public String postEntity(@RequestBody User user) {
        redisTemplate.opsForValue().set(user.getUserCode(), user);
        return "SUCCESS";
    }

    // 获取对象
    @GetMapping("/getEntity/{key}")
    public User getEntity(@PathVariable(name = "key") String key) {
        return (User) redisTemplate.opsForValue().get(key);
    }

}

【测试】

1、保存字符串
SprinBoot2.x 整合 Redis_第2张图片
Redis库
SprinBoot2.x 整合 Redis_第3张图片

2、获取字符串
SprinBoot2.x 整合 Redis_第4张图片
3、保存对象
SprinBoot2.x 整合 Redis_第5张图片
Redis库
SprinBoot2.x 整合 Redis_第6张图片
4、获取对象
SprinBoot2.x 整合 Redis_第7张图片
OK,一切大功告成!


【遇到问题】

调用接口时报“ERR Client sent AUTH, but no password is set”错误,问题是需要配置Redis的配置文件中密码的设置导致的

解决办法参考下文:
https://blog.csdn.net/weixin_34203426/article/details/86031339


【其他文章】

SpringBoot 使用 Redis 缓存

你可能感兴趣的:(Redis,SpringBoot)