程序员子龙(Java面试 + Java学习) 程序员子龙(Java面试 + Java学习)
首页
学习指南
工具
开源项目
技术书籍

程序员子龙

Java 开发从业者
首页
学习指南
工具
开源项目
技术书籍
  • 基础

  • JVM

  • Spring

  • 并发编程

  • Mybatis

  • 网络编程

  • 数据库

  • 缓存

  • 设计模式

  • 分布式

  • 高并发

  • SpringBoot

    • SpringBoot 整合redis
      • SpringBoot 线程池
      • springboot下整合mybatis
      • spring boot 配置文件的加载顺序
      • springboot启动不加载bootstrap.yml文件的问题解决
      • SpringBoot设置动态定时任务
      • springboot整合hibernate
      • ApplicationRunner、InitializingBean、@PostConstruct使用详解
      • Spring Boot 优雅的参数校验方案
      • ELK处理 SpringBoot 日志,太优雅了!
      • SpringBoot配置数据源
      • Spring Boot 默认数据库连接池 —— HikariCP
      • 数据库连接池Hikari监控
      • Spring Boot中使用AOP统一处理Web请求日志
      • SpringBoot 三大开发工具,你都用过么?
      • Spring Boot 3.2 + CRaC = 王炸!
      • springboot启动的时候排除加载某些bean
      • spring boot中集成swagger
      • springboot项目引入这个包以后把原来的json报文改为了xml格式返回
      • SpringBoot中new对象不能自动注入对象和属性的问题
      • 使用 Spring Boot Actuator 监控应用
      • 记录一次springboot自动任务线上突然不执行问题排查过程
      • SpringBoot定时任务@Scheduled源码解析
      • Spring Boot + Lua = 王炸!
      • Spring Boot 实现定时任务动态管理
      • SpringBoot的@Async注解有什么坑?
      • druid 参数配置详解
      • Spring Boot HandlerMethodArgumentResolver 使用和场景
      • SpringBoot数据加解密
      • 解决controller层注入的service为null
      • 在 Spring Boot 中通过 RequestBodyAdvice 统一解码请求体
      • SpringBoot之使用Redisson实现分布式锁(含完整例子)
    • SpringCloudAlibaba

    • Nginx

    • 面试

    • 生产问题

    • 系统设计

    • 消息中间件

    • Java
    • SpringBoot
    程序员子龙
    2024-01-29
    目录

    SpringBoot 整合redis

    # 引入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    
    1
    2
    3
    4
    5
    6
    7
    8

    Spring Boot 提供了对 Redis 集成的组件包:spring-boot-starter-data-redis,spring-boot-starter-data-redis依赖于spring-data-redis 和 lettuce 。Spring Boot 1.0 默认使用的是 Jedis 客户端,2.0 替换成 Lettuce。

    Lettuce 是一个可伸缩线程安全的 Redis 客户端,多个线程可以共享同一个 RedisConnection,它利用优秀 netty NIO 框架来高效地管理多个连接。

    # 配置数据源

    application.properties

    # Redis数据库索引(默认为0)
    spring.redis.database=0  
    # Redis服务器地址
    spring.redis.host=localhost
    # Redis服务器连接端口
    spring.redis.port=6379  
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    # 连接池最大连接数(使用负值表示没有限制) 默认 8
    spring.redis.lettuce.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
    spring.redis.lettuce.pool.max-wait=-1
    # 连接池中的最大空闲连接 默认 8
    spring.redis.lettuce.pool.max-idle=8
    # 连接池中的最小空闲连接 默认 0
    spring.redis.lettuce.pool.min-idle=0
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    # 数据访问层dao

    @Repository
    public class RedisDao {
    
        @Autowired
        private StringRedisTemplate template;
    
        public  void setKey(String key,String value){
            template.opsForValue().set(key,value,1, TimeUnit.MINUTES);//1分钟过期
        }
    
        public String getValue(String key){
            return this.template.opsForValue().get(key);
        }
    
    
        public void setHash(String key,String filed,String value){
            template.opsForHash().put(key,filed,value);
        }
    
        public Object getHash(String key,String filed){
            return template.opsForHash().get(key, filed);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23

    # 单元测试

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringbootRedisApplicationTests {
    
    	public static Logger logger= LoggerFactory.getLogger(SpringbootRedisApplicationTests.class);
    
    	@Autowired
    	RedisDao redisDao;
    
    	@Test
    	public void testRedis(){
    		redisDao.setKey("name","hello");
    		redisDao.setKey("age","11");
    		logger.info(redisDao.getValue("name"));
    		logger.info(redisDao.getValue("age"));
    
    		redisDao.setHash("testHash","hello","world");
    		logger.info("value:"+ redisDao.getHash("testHash","hello"));
    	}
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    c.demo.SpringbootRedisApplicationTests : hello c.demo.SpringbootRedisApplicationTests : 11

    c.demo.SpringbootRedisApplicationTests : value:world

    # 解决java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use

    单元测试报这个错误,原因是测试类的包名与启动器的包名不一致。

    解决方法:Spring Boot测试类包名与main下application.class启动类的包名默认要一致,修改包名后问题得以解决!

    # 利用AOP自动缓存

    添加 cache 的配置类

    
    //@EnableCaching来开启缓存。
    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
        
        @Bean
        public KeyGenerator keyGenerator() {
    
            return new KeyGenerator() {
                @Override
                public Object generate(Object target, Method method, Object... params) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(target.getClass().getName());
                    sb.append(method.getName());
                    for (Object obj : params) {
                        sb.append(obj.toString());
                    }
                    return sb.toString();
                }
            };
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23

    测试:

    @RestController
    public class CityController {
    
        @RequestMapping("/getCity")
        @Cacheable(value="city-key")
        public City getCity() {
    
            City city = new City("北京","首都");
            System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
            return city;
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    上次更新: 2024/01/30, 15:08:57
    一个注解,优雅的实现接口幂等性
    SpringBoot 线程池

    ← 一个注解,优雅的实现接口幂等性 SpringBoot 线程池→

    最近更新
    01
    一个注解,优雅的实现接口幂等性
    11-17
    02
    MySQL事务(超详细!!!)
    10-14
    03
    阿里二面:Kafka中如何保证消息的顺序性?这周被问到两次了
    10-09
    更多文章>
    Theme by Vdoing | Copyright © 2024-2024

        辽ICP备2023001503号-2

    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式