一,IDEA新建一个spring boot项目
二,在pom.xml文件添加相关redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加相关依赖之后,刷新maven库
三,修改相关配置
server.port=8081
#redis相关配置
#redis服务地址
spring.redis.host=172.19.8.224
#redis的端口号
spring.redis.port=6379
#redis的默认库为0号库
spring.redis.database=0
注意:在springboot连接redis之前,要确保redis远程连接必须开启
- 首先修改redis.conf文件(redis默认是没有配置文件的,必须从安装目录拷贝到
/usr/redis
下,参考命令:cp redis.conf /usr/redis/
):
[root@Cluster-01 ~]# cd /usr/redis
[root@Cluster-01 redis]# ls
bin redis.conf
[root@Cluster-01 redis]# cd bin
[root@Cluster-01 bin]# cd ..
[root@Cluster-01 redis]# vim redis.conf
- 修改完配置文件之后,重新启动redis时,必须执行配置文件启动:
[root@Cluster-01 bin]# ./redis-server ../redis.conf
四,在test文件中添加一个TestStringRedisTemplate测试类
代码块:
package com.wx;
import org.junit.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.connection.DataType;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Set;
//启动springboot应用
@SpringBootTest(classes =RedisApplication.class )
@RunWith(SpringRunner.class)
public class TestStringRedisTemplate {
//注入springredisTemplate
@Autowired
private StringRedisTemplate stringRedisTemplate;
//操作redis中的字符串
@Test
public void testString(){
stringRedisTemplate.opsForValue().set("name","文文");
String value=stringRedisTemplate.opsForValue().get("name");
System.out.println("value="+value);
}
//操作redis中的key相关
@Test
public void testkey(){
stringRedisTemplate.delete("name");//删除一个key;
Boolean hasKey=stringRedisTemplate.hasKey("name");//判断某个key是否存在
System.out.println(hasKey);
DataType name=stringRedisTemplate.type("name");//判断key所对应值得类型
System.out.println(name);
Set<String> keys=stringRedisTemplate.keys("*");//获取所有key
keys.forEach(key -> System.out.println("key="+key));
}
}
执行结果:
也可以去redis终端执行命令查看结果:
[root@Cluster-01 bin]# ./redis-cli -h localhost -p 6379
localhost:6379> keys *
1) "age"
2) "name"
localhost:6379> get name
"\xe6\x96\x87\xe9\x91\xab"
localhost:6379>
注意:这里"\xe6\x96\x87\xe9\x91\xab"
,localhost:6379> get name 之后不显示中文的原因,是需要执行
–raw`命令执行redis
[root@Cluster-01 bin]# ./redis-cli -h localhost -p 6379 --raw
即可显示中文