一、简介
redis是一种可以持久存储的缓存系统,是一个高性能的key-value数据库。
二、使用
2.1、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.2、application.properties配置
#########################redis开始######################### spring.redis.host=192.168.175.13 spring.redis.port=6379 spring.redis.password=123456 #spring.redis.database=0 #spring.redis.pool.max-active=8 #spring.redis.pool.max-idle=8 #spring.redis.pool.max-wait=-1 #spring.redis.pool.min-idle=0 #spring.redis.timeout=0 #########################redis结束#########################
2.3、服务类
package com.example.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
* Redis服务类
*
* @Author: 我爱大金子
* @Description: Redis服务类
* @Date: Create in 12:02 2017/7/3
*/
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void set(String key, String value) {
ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
if (!this.stringRedisTemplate.hasKey(key)) {
ops.set(key, value);
System.out.println("set key success");
} else { // 存在则打印之前的 value 值
System.out.println("this key = " + ops.get(key));
}
}
public String get(String key) {
return this.stringRedisTemplate.opsForValue().get(key);
}
public void del(String key) {
this.stringRedisTemplate.delete(key);
}
}2.4、测试
package com.example.demo;
import com.example.demo.utils.RedisUtil;
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.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {
@Autowired
private RedisUtil redisUtil;
@Test
public void set() {
redisUtil.set("liuy", "你好");
}
@Test
public void get() {
System.out.println(redisUtil.get("liuy"));
}
@Test
public void del() {
redisUtil.del("liuy");
}
}执行set:
执行get:
执行del:
本文出自 “我爱大金子” 博客,请务必保留此出处http://1754966750.blog.51cto.com/7455444/1944008
原文地址:http://1754966750.blog.51cto.com/7455444/1944008