Springboot整合redis从安装到FLUSHALL

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: Springboot整合redis从安装到FLUSHALL

语言: java+kotlin

windows下安装redis

参考 https://www.cnblogs.com/jaign/articles/7920588.html

安装redis可视化工具 Redis Desktop Manager

参考 https://www.cnblogs.com/zheting/p/7670154.html

依赖

    compile('org.springframework.boot:spring-boot-starter-data-redis')

application.yml配置

spring:
 # redis
  redis:
    database: 0
    host: localhost
    port: 6379
    password: 12345
    jedis:
      pool:
        max-active: 10
        min-idle: 0
        max-idle: 8
    timeout: 10000

redis配置类 new RedisConfiguration

package com.futao.springmvcdemo.foundation.configuration

import org.springframework.cache.CacheManager
import org.springframework.cache.annotation.CachingConfigurerSupport
import org.springframework.cache.annotation.EnableCaching
import org.springframework.cache.interceptor.KeyGenerator
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
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.StringRedisSerializer
import javax.annotation.Resource

/**
 * redis配置类
 *
 * @author futao
 * Created on 2018/10/16.
 *
 * redisTemplate.opsForValue();//操作字符串
 * redisTemplate.opsForHash();//操作hash
 * redisTemplate.opsForList();//操作list
 * redisTemplate.opsForSet();//操作set
 * redisTemplate.opsForZSet();//操作有序set
 *
 */
@Configuration
@EnableCaching
open class RedisConfiguration : CachingConfigurerSupport() {

    /**
     * 自定义redis key的生成规则
     */
    @Bean
    override fun keyGenerator(): KeyGenerator {
        return KeyGenerator { target, method, params ->
            val builder = StringBuilder()
            builder.append("${target.javaClass.simpleName}-")
                    .append("${method.name}-")
            for (param in params) {
                builder.append("$param-")
            }
            builder.toString().toLowerCase()
        }
    }

    /**
     * 自定义序列化
     * 这里的FastJsonRedisSerializer引用的自己定义的
     */
    @Bean
    open fun redisTemplate(factory: RedisConnectionFactory): RedisTemplate<String, Any> {
        val redisTemplate = RedisTemplate<String, Any>()
        val fastJsonRedisSerializer = FastJsonRedisSerializer(Any::class.java)
        val stringRedisSerializer = StringRedisSerializer()
        return redisTemplate.apply {
            defaultSerializer = fastJsonRedisSerializer
            keySerializer = stringRedisSerializer
            hashKeySerializer = stringRedisSerializer
            valueSerializer = fastJsonRedisSerializer
            hashValueSerializer = fastJsonRedisSerializer
            connectionFactory = factory
        }
    }

    @Resource
    lateinit var redisConnectionFactory: RedisConnectionFactory

    override fun cacheManager(): CacheManager {
        return RedisCacheManager.create(redisConnectionFactory)
    }
}

自定义redis中数据的序列化与反序列化 new FastJsonRedisSerializer

package com.futao.springmvcdemo.foundation.configuration

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import com.futao.springmvcdemo.model.system.SystemConfig
import org.springframework.data.redis.serializer.RedisSerializer
import java.nio.charset.Charset

/**
 *  自定义redis中数据的序列化与反序列化
 *
 * @author futao
 * Created on 2018/10/17.
 */
class FastJsonRedisSerializer<T>(java: Class<T>) : RedisSerializer<T> {

    private val clazz: Class<T>? = null

    /**
     * Serialize the given object to binary data.
     *
     * @param t object to serialize. Can be null.
     * @return the equivalent binary data. Can be null.
     */
    override fun serialize(t: T?): ByteArray? {
        return if (t == null) {
            null
        } else {
            JSON.toJSONString(t, SerializerFeature.WriteClassName).toByteArray(Charset.forName(SystemConfig.UTF8_ENCODE))
        }
    }

    /**
     * Deserialize an object from the given binary data.
     *
     * @param bytes object binary representation. Can be null.
     * @return the equivalent object instance. Can be null.
     */
    override fun deserialize(bytes: ByteArray?): T? {
        return if (bytes == null || bytes.isEmpty()) {
            null
        } else {
            val string = String(bytes, Charset.forName(SystemConfig.UTF8_ENCODE))
            JSON.parseObject(string, clazz) as T
        }
    }
}

使用

1. 基于注解的方式

  • @Cacheable() redis中的key会根据我们的keyGenerator方法来生成,比如对应下面这个例子,如果曾经以mobile,pageNum,pageSize,orderBy的值执行过list这个方法的话,方法返回的值会存在redis缓存中,下次如果仍然以相同的mobile,pageNum,pageSize,orderBy的值来调用这个方法的话会直接返回缓存中的值
@Service
public class UserServiceImpl implements UserService {
    @Override
    @Cacheable(value = "user")
    public List<User> list(String mobile, int pageNum, int pageSize, String orderBy) {
        PageResultUtils<User> pageResultUtils = new PageResultUtils<>();
        final val sql = pageResultUtils.createCriteria(User.class.getSimpleName())
                                       .orderBy(orderBy)
                                       .page(pageNum, pageSize)
                                       .getSql();
        return userDao.list(sql);
    }
}
  • 测试
  • 第一次请求(可以看到执行了sql,数据是从数据库中读取的)
    第一次请求
  • 通过redis desktop manager查看redis缓存中已经存储了我们刚才list返回的值
    image.png

    • 后续请求(未执行sql,直接读取的是redis中的值)
      后续请求

2. 通过java代码手动set与get

package com.futao.springmvcdemo.controller

import com.futao.springmvcdemo.model.entity.User
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import javax.annotation.Resource

/**
 * @author futao
 * Created on 2018/10/17.
 */
@RestController
@RequestMapping(path = ["kotlinTest"], produces = [MediaType.APPLICATION_JSON_UTF8_VALUE])
open class KotlinTestController {

    @Resource
    private lateinit var redisTemplate: RedisTemplate<Any, Any>

    /**
     * 存入缓存
     */
    @GetMapping(path = ["setCache"])
    open fun cache(
            @RequestParam("name") name: String,
            @RequestParam("age") age: Int
    ): User {
        val user = User().apply {
            username = name
            setAge(age.toString())
        }
        redisTemplate.opsForValue().set(name, user)
        return user
    }


    /**
     * 获取缓存
     */
    @GetMapping(path = ["getCache"])
    open fun getCache(
            @RequestParam("name") name: String
    ): User? {
        return if (redisTemplate.opsForValue().get(name) != null) {
            redisTemplate.opsForValue().get(name) as User
        } else null
    }
}
  • 测试结果
  • 请求(序列化)
    image.png
  • redis desktop manager中查看
    查看

    • 读取(反序列化)
      读取

  • 使用注解的方式存入的数据使用redis desktop manager或者redis-cli --raw查看显示的是编码之后的,但是使用java代码手动set并不会出现这样的问题(后期需要检查使用注解的方式是不是走了自定义的序列化)

TODO

  • redis数据的持久化
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
2月前
|
编解码 NoSQL Java
使用Spring Boot + Redis 队列实现视频文件上传及FFmpeg转码的技术分享
【8月更文挑战第30天】在当前的互联网应用中,视频内容的处理与分发已成为不可或缺的一部分。对于视频平台而言,高效、稳定地处理用户上传的视频文件,并对其进行转码以适应不同设备的播放需求,是提升用户体验的关键。本文将围绕使用Spring Boot结合Redis队列技术来实现视频文件上传及FFmpeg转码的过程,分享一系列技术干货。
88 3
|
8天前
|
JSON NoSQL Java
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
这篇文章介绍了在Java中使用Redis客户端的几种方法,包括Jedis、SpringDataRedis和SpringBoot整合Redis的操作。文章详细解释了Jedis的基本使用步骤,Jedis连接池的创建和使用,以及在SpringBoot项目中如何配置和使用RedisTemplate和StringRedisTemplate。此外,还探讨了RedisTemplate序列化的两种实践方案,包括默认的JDK序列化和自定义的JSON序列化,以及StringRedisTemplate的使用,它要求键和值都必须是String类型。
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
|
10天前
|
NoSQL Linux Redis
linux安装单机版redis详细步骤,及python连接redis案例
这篇文章提供了在Linux系统中安装单机版Redis的详细步骤,并展示了如何配置Redis为systemctl启动,以及使用Python连接Redis进行数据操作的案例。
20 2
|
1月前
|
NoSQL 关系型数据库 Redis
mall在linux环境下的部署(基于Docker容器),Docker安装mysql、redis、nginx、rabbitmq、elasticsearch、logstash、kibana、mongo
mall在linux环境下的部署(基于Docker容器),docker安装mysql、redis、nginx、rabbitmq、elasticsearch、logstash、kibana、mongodb、minio详细教程,拉取镜像、运行容器
mall在linux环境下的部署(基于Docker容器),Docker安装mysql、redis、nginx、rabbitmq、elasticsearch、logstash、kibana、mongo
|
10天前
|
NoSQL Linux Redis
linux之centos安装redis
linux之centos安装redis
|
2月前
|
缓存 NoSQL Linux
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
|
1天前
|
存储 NoSQL Java
Spring Boot项目中使用Redis实现接口幂等性的方案
通过上述方法,可以有效地在Spring Boot项目中利用Redis实现接口幂等性,既保证了接口操作的安全性,又提高了系统的可靠性。
6 0
|
2月前
|
NoSQL Redis 数据安全/隐私保护
深入探索利用Docker安装Redis
【8月更文挑战第27天】
91 2
|
2月前
|
Web App开发 前端开发 关系型数据库
基于SpringBoot+Vue+Redis+Mybatis的商城购物系统 【系统实现+系统源码+答辩PPT】
这篇文章介绍了一个基于SpringBoot+Vue+Redis+Mybatis技术栈开发的商城购物系统,包括系统功能、页面展示、前后端项目结构和核心代码,以及如何获取系统源码和答辩PPT的方法。
|
2月前
|
监控 NoSQL Redis
【redis】redis 单实例标准安装
【redis】redis 单实例标准安装
下一篇
无影云桌面