一、准备工作
首先创建一个空工程,然后在该空工程创建一个模块(选择Spring Initializal),选择Spring Data Redis依赖。
pomx.xml
xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0modelVersion> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>2.2.4.RELEASEversion> <relativePath/> parent> <groupId>com.spring.boot.examplegroupId> <artifactId>spring-boot-redisartifactId> <version>0.0.1-SNAPSHOTversion> <name>spring-boot-redisname> <description>Demo project for Spring Bootdescription> <properties> <java.version>1.8java.version> properties> <dependencies>
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-redisartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> <exclusions> <exclusion> <groupId>org.junit.vintagegroupId> <artifactId>junit-vintage-engineartifactId> exclusion> exclusions> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
下载redis
链接: https://pan.baidu.com/s/1w4Ka6ehyGI1cp9hHBwQZUw 提取码: zrvs
解压后这个文件夹,在windows下运行redis-server,就启动了redis服务。
运行redis-cli.ext就运行了客户端,客户端中可直接使用redis原生的各种命令。
也可使用下载的redis管理软件。
二、配置
在applicatin.properties中配置reids地址和端口
#redis地址和端口
spring.redis.host=127.0.0.1
spring.redis.port=6379
现在我们来测试下:
在test文件夹下一直点,找到创建SpringBoot模块时生成的测试类。
package com.spring.boot.example.springboot.redis;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
//没有RunWith解决方法在下面
@RunWith(SpringJUnit4ClassRunner.class)
class SpringBootRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void testRedis() {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("key","value");
String key = (String)valueOperations.get("key");
System.out.println(key);
}
}
运行 testRedis方法,成功将值存入redis,并将其取出。
再来看下redis有没有数据
虽然值有点奇怪,但依稀可见key和value。
存入redis时,未配置序列化方法的情况下默认使用jdk的序列化方式,存入的结果是jdk序列化之后的结果就会这样显示。
Original: https://www.cnblogs.com/huang-changfan/p/12257666.html
Author: gcmh
Title: Spring整合Redis
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/588437/
转载文章受原作者版权保护。转载请注明原作者出处!