Springboot整合redis从安装到FLUSHALL

本文涉及的产品
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
云原生内存数据库 Tair,内存型 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
目录
相关文章
|
5天前
|
NoSQL 数据可视化 Redis
Mac安装Redis
Mac安装Redis
16 3
|
5天前
|
NoSQL Ubuntu 安全
在Ubuntu 18.04上安装和保护Redis的方法
在Ubuntu 18.04上安装和保护Redis的方法
16 0
|
2天前
|
NoSQL Redis 数据安全/隐私保护
Redis6入门到实战------ 二、Redis安装
这篇文章详细介绍了Redis 6的安装过程,包括下载、解压、编译、安装、配置以及启动Redis服务器的步骤。还涵盖了如何设置Redis以在后台运行,如何为Redis设置密码保护,以及如何配置Redis服务以实现开机自启动。
Redis6入门到实战------ 二、Redis安装
|
2天前
|
缓存 NoSQL Java
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解、如何添加锁解决缓存击穿问题?分布式情况下如何添加分布式锁
这篇文章介绍了如何在SpringBoot项目中整合Redis,并探讨了缓存穿透、缓存雪崩和缓存击穿的问题以及解决方法。文章还提供了解决缓存击穿问题的加锁示例代码,包括存在问题和问题解决后的版本,并指出了本地锁在分布式情况下的局限性,引出了分布式锁的概念。
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解、如何添加锁解决缓存击穿问题?分布式情况下如何添加分布式锁
|
2天前
|
缓存 NoSQL Java
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解分布式情况下如何添加分布式锁 【续篇】
这篇文章是关于如何在SpringBoot应用中整合Redis并处理分布式场景下的缓存问题,包括缓存穿透、缓存雪崩和缓存击穿。文章详细讨论了在分布式情况下如何添加分布式锁来解决缓存击穿问题,提供了加锁和解锁的实现过程,并展示了使用JMeter进行压力测试来验证锁机制有效性的方法。
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解分布式情况下如何添加分布式锁 【续篇】
|
2天前
|
NoSQL Java Redis
Redis6入门到实战------ 八、Redis与Spring Boot整合
这篇文章详细介绍了如何在Spring Boot项目中整合Redis,包括在`pom.xml`中添加依赖、配置`application.properties`文件、创建配置类以及编写测试类来验证Redis的连接和基本操作。
Redis6入门到实战------ 八、Redis与Spring Boot整合
|
2天前
|
NoSQL 数据可视化 Linux
2022 年超详细步骤讲解 CentOS 7 安装Redis 。解决Redis Desktop Manager 图形化工具连接失败解决 ;connection failed处理。开机自启Redis
这篇文章提供了在CentOS 7上安装Redis的详细步骤,包括上传Redis安装包、解压安装、编译、安装、备份配置文件、修改配置以支持后台运行和设置密码、启动Redis服务、使用客户端连接Redis、关闭Redis服务、解决Redis Desktop Manager图形化工具连接失败的问题、设置Redis开机自启动,以及Redis服务的启动和停止命令。
2022 年超详细步骤讲解 CentOS 7 安装Redis 。解决Redis Desktop Manager 图形化工具连接失败解决 ;connection failed处理。开机自启Redis
|
2天前
|
NoSQL JavaScript Java
SpringBoot+Vue+Redis实现验证码功能、一个小时只允许发三次验证码。一次验证码有效期二分钟。SpringBoot整合Redis
这篇文章介绍了如何使用SpringBoot、Vue和Redis实现验证码功能,包括验证码的有效期控制和每小时发送次数限制,以及具体的实现步骤和效果演示。
|
2天前
|
NoSQL 数据可视化 Linux
一文教会你如何在Linux系统中使用Docker安装Redis 、以及如何使用可视化工具连接【详细过程+图解】
这篇文章详细介绍了如何在Linux系统中使用Docker安装Redis,并提供了使用可视化工具连接Redis的步骤。内容包括安装Redis镜像、创建外部配置文件、映射文件和端口、启动和测试Redis实例、配置数据持久化存储,以及使用可视化工具连接和操作Redis数据库的过程。
|
5天前
|
存储 NoSQL Java
基于SpringBoot+Redis实现查找附近用户的功能
使用Redis的GEO命令结合SpringBoot实现查找附近用户的功能,通过`GEOADD`命令添加地理位置信息和`GEORADIUS`命令查询附近用户。
11 0