zoukankan      html  css  js  c++  java
  • 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

    来操作复杂类型的数据。

  • 相关阅读:
    CodeBlocks "no such file or directory" 错误解决方案(创建类找不到头文件)
    WCF配置文件与文件下载之坎坷路
    使用Visual Studio 2010打造C语言编译器
    一个小程序引发的思考
    在C#使用文件监控对象FileSystemWatcher 实现数据同步
    C 语言 static、extern与指针函数介绍
    检测端口是否被占用
    C# ini文件读写类
    C学习笔记(2)--指针
    plsql auto 常用语法
  • 原文地址:https://www.cnblogs.com/zifeiy/p/9932449.html
Copyright © 2011-2022 走看看