[原创]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
        }
    }
}

# 启动类

package com.futao.springmvcdemo;

import com.alibaba.fastjson.parser.ParserConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;

/**
 * @author futao
 * ServletComponentScan 开启servlet和filter
 */
@SpringBootApplication
@ServletComponentScan
@MapperScan("com.futao.springmvcdemo.dao")
@EnableCaching
//@EnableAspectJAutoProxy
public class SpringmvcdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringmvcdemoApplication.class, args);
        /**
         * redis反序列化
         * 开启fastjson反序列化的autoType
         */
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }
}

# 使用

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数据的持久化

我在这里等你:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容

  • 重点参考链接: http://www.cnblogs.com/wangyuyu/p/3786236.html Re...
    Kevin_Junbaozi阅读 2,136评论 0 21
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,050评论 18 139
  • 让我想起奇迹男孩,勇敢乐观面对,才让有缺陷的人们,对生活充满信心。 乐观,不放弃,对着梦想勇往直前。 最终收获掌声...
    不好听的时光阅读 415评论 0 0
  • 我不喜欢侦探推理小说,因为我比较笨啊,推理不出凶手,这对一个生活骄傲的人来说,就好像是把他的头按在地上大声对他吼道...
    角角散步去阅读 385评论 1 3
  • 这两天一直咳嗽,而且前两天咳出一小块白色物质,怀疑是钙化物,今天又咳出白色物质,和之前一样
    高柯阅读 159评论 0 0