栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Redis】SpringBoot整合Redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Redis】SpringBoot整合Redis

SpringBoot整合Redis
  • Redis简介
  • 导入依赖
  • 配置yml
  • 编写自己的redisTemplate
  • 添加与使用

Redis简介

REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库。Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库,并提供多种语言的 API。Redis 通常被称为数据结构服务器,因为值(value)可以是字符串(String)、哈希(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等类型。

导入依赖

    org.springframework.boot
    spring-boot-starter-data-redis


    org.apache.commons
    commons-pool2

配置yml
spring:
  redis:
    database: 0  #Redis数据库索引(默认为0)
    host: 127.0.0.1  #Redis服务器地址
    port: 6379  #Redis服务器连接端口
    lettuce:
      pool:
        max-active: 8  #连接池最大连接数(使用负值表示没有限制)
        max-wait: 10000ms  #最大阻塞等待时间(负数表示没有限制)
        max-idle: 50  #连接池中的最大空闲连接
        min-idle: 5   #连接池中的最小空闲连接
编写自己的redisTemplate
@Configuration
@EnableCaching
public class RedisConfig {
    
    @Bean
    public RedisTemplate redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
        final RedisTemplate redisTemplate = new RedisTemplate<>();
        //对Key和Value进行序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //对HashMap进行序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}
添加与使用

将数据添加到redis中(在service层)

@Autowired
private RedisTemplate redisTemplate;

public String getContentByType(final String type) {
        final String contentByType = this.systemConfigMapper.getContentByType(type);
        this.redisTemplate.opsForValue().set("system" + type, contentByType);
        return contentByType;
    }

取出使用(在controller层),通过key取出,判断是否为空,不为空则直接返回,相反则须在数据库中查询返回

@ApiOperation("查找配置信息")
@GetMapping("/seekContent/{type}")
public String getContentByType(@PathVariable("type") final String type) {
     log.info("进入了查找配置信息接口");
     final Object o = this.redisTemplate.opsForValue().get("system" + type);
     if (o != null) {
          return JSON.toJSONString(o);
     }
     return JSON.toJSONString(this.systemConfigService.getContentByType(type));
}

欢迎大家加入qq交流群:251413523,一起学习一起秃头。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/696740.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号