SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理

Easter79
• 阅读 452
本文源码
GitHub:知了一笑
https://github.com/cicadasmile/spring-boot-base

一、Redis简介

Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch。这些案例整理好后,陆续都会上传Git。

SpringBoot2 版本,支持的组件越来越丰富,对Redis的支持不仅仅是扩展了API,更是替换掉底层Jedis的依赖,换成Lettuce。 本案例需要本地安装一台Redis数据库。

二、Spring2.0集成Redis

1、核心依赖

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

2、配置文件

# 端口
server:
  port: 8008
spring:
  application:
    # 应用名称
    name: node08-boot-redis
  # redis 配置
  redis:
    host: 127.0.0.1
    #超时连接
    timeout: 1000ms
    jedis:
      pool:
        #最大连接数据库连接数,设 0 为没有限制
        max-active: 8
        #最大等待连接中的数量,设 0 为没有限制
        max-idle: 8
        #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        max-wait: -1ms
        #最小等待连接中的数量,设 0 为没有限制
        min-idle: 0

这样Redis的环境就配置成功了,已经可以直接使用封装好的API了。

3、简单测试案例

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@RestController
public class RedisController {
    @Resource
    private StringRedisTemplate stringRedisTemplate ;
    @RequestMapping("/setGet")
    public String setGet (){
        stringRedisTemplate.opsForValue().set("cicada","smile");
        return stringRedisTemplate.opsForValue().get("cicada") ;
    }
    @Resource
    private RedisTemplate redisTemplate ;
    /**
     * 设置 Key 的有效期 10 秒
     */
    @RequestMapping("/setKeyTime")
    public String setKeyTime (){
        redisTemplate.opsForValue().set("timeKey","timeValue",10, TimeUnit.SECONDS);
        return "success" ;
    }
    @RequestMapping("/getTimeKey")
    public String getTimeKey (){
        // 这里 Key 过期后,返回的是字符串 'null'
        return String.valueOf(redisTemplate.opsForValue().get("timeKey")) ;
    }
}

4、自定义序列化配置

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * Redis 配置
 */
@Configuration
public class RedisConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class) ;
    /**
     * 序列化配置
     */
    @Bean
    public RedisTemplate<string, serializable> redisTemplate
            (LettuceConnectionFactory  redisConnectionFactory) {
        LOGGER.info("RedisConfig == &gt;&gt; redisTemplate ");
        RedisTemplate<string, serializable> template = new RedisTemplate&lt;&gt;();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

5、序列化测试

import com.boot.redis.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RestController
public class SerializeController {
    @Resource
    private RedisTemplate redisTemplate ;
    @RequestMapping("/setUser")
    public String setUser (){
        User user = new User() ;
        user.setName("cicada");
        user.setAge(22);
        List<string> list = new ArrayList&lt;&gt;() ;
        list.add("小学");
        list.add("初中");
        list.add("高中");
        list.add("大学");
        user.setEducation(list);
        redisTemplate.opsForValue().set("userInfo",user);
        return "success" ;
    }
    @RequestMapping("/getUser")
    public User getUser (){
        return (User)redisTemplate.opsForValue().get("userInfo") ;
    }
}

三、源代码地址

GitHub地址:知了一笑
https://github.com/cicadasmile/spring-boot-base
码云地址:知了一笑
https://gitee.com/cicadasmile/spring-boot-base

SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理 SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理 </string,></string,>

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Stella981 Stella981
2年前
SpringBoot2.0 基础案例(08):集成Redis数据库,实现缓存管理
本文源码GitHub:知了一笑https://github.com/cicadasmile/springbootbase一、Redis简介SpringBoot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis,Mo
Stella981 Stella981
2年前
Spring Boot 与 Kotlin 使用Redis数据库
SpringBoot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis,MongoDB,Elasticsearch,Solr和Cassandra。使用RedisRedis是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、K
Stella981 Stella981
2年前
SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口
本文源码GitHub:知了一笑https://github.com/cicadasmile/springbootbase一、SpringBoot框架的特点1、SpringBoot2.0特点1)SpringBoot继承了Spri
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Stella981 Stella981
2年前
Nginx + lua +[memcached,redis]
精品案例1、Nginxluamemcached,redis实现网站灰度发布2、分库分表/基于Leaf组件实现的全球唯一ID(非UUID)3、Redis独立数据监控,实现订单超时操作/MQ死信操作SelectPollEpollReactor模型4、分布式任务调试Quartz应用
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Easter79 Easter79
2年前
SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口
本文源码GitHub:知了一笑https://github.com/cicadasmile/springbootbase一、SpringBoot框架的特点1、SpringBoot2.0特点1)SpringBoot继承了Spri
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k