• Spring Boot集成Redis缓存


    首先在pom.xml中引入所需的依赖:

    		<dependency>
    		    <groupId>org.springframework.boot</groupId>
    		    <artifactId>spring-boot-starter-data-redis</artifactId>
    		</dependency>
    

    然后在applications.properties中添加相关配置:

    ### Redis缓存配置
    ### 默认redis数据库为db0
    spring.redis.database=0
    ### 服务器地址,默认为localhost
    spring.redis.host=localhost
    ### 链接端口,默认为6379
    spring.redis.port=6379
    ### redis密码默认为空
    spring.redis.password=
    

    然后编辑src/test/java下的TestApplicationTests.java文件:

    package com.zifeiy.test;
    
    import javax.annotation.Resource;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestApplicationTests {
    	
    	@Resource
    	private RedisTemplate redisTemplate;
    	
    	@Resource
    	private StringRedisTemplate stringRedisTemplate;
    	
    	@Test
    	public void testRedis() {
    		redisTemplate.opsForValue().set("name", "zifeiy");
    		String name = (String) redisTemplate.opsForValue().get("name");
    		System.out.println("1: " + name);
    		redisTemplate.delete("name");
    		redisTemplate.opsForValue().set("name", "zifeiy");
    		name = stringRedisTemplate.opsForValue().get("name");
    		System.out.println("2: name");
    	}
    }
    

    输出结果如下:

    1: zifeiy
    2: name
    

    这里的RedisTemplate和StringRedisTemplate都是Redis Data Redis为我们提供的模板类,用来对Redis数据库进行操作。他们除了提供opsForValue方法来操作简单属性数据外,还提供以下数据访问方法:

    • opsForList
    • opsForSet
    • opsForZSet
    • opsForHash

    来操作复杂类型的数据。

  • 相关阅读:
    loj#2020. 「AHOI / HNOI2017」礼物
    loj#117. 有源汇有上下界最小流
    loj#6491. zrq 学反演
    loj#6261. 一个人的高三楼
    loj#528. 「LibreOJ β Round #4」求和
    2018-2019 ACM-ICPC Brazil Subregional Programming Contest
    2015-2016 ACM-ICPC, NEERC, Moscow Subregional Contest J
    2015-2016 ACM-ICPC Northeastern European Regional Contest (NEERC 15)C
    addEventListener() 和 removeEventListener()
    9个图片滑块动画
  • 原文地址:https://www.cnblogs.com/zifeiy/p/9932449.html
Copyright © 2020-2023  润新知