新建一个Springboot工程,如果工程没有建好,请看SpringBoot Gradle 项目创建。
一、build.gradle添加依赖
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.0.0.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis
compile group: 'org.springframework.boot', name: 'spring-boot-starter-redis', version: '1.4.7.RELEASE'
// https://mvnrepository.com/artifact/redis.clients/jedis
compile group: 'redis.clients', name: 'jedis', version: '2.9.0'二
二、application.properties添加连接配置
#redis
spring.redis.host=192.168.3.45
spring.redis.port=6379
#spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0
如果有密码,去掉spring.redis.password注释,添加密码
三、Dao层编写
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.Repository;
import java.util.concurrent.TimeUnit;
/**
* Created by wzj on 2018/3/28.
*/
@Repository
public class RedisDao
{
/**
* 注入
*/
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void setKey(String key, String value)
{
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
ops.set(key, value, 3, TimeUnit.SECONDS);//设置过期时间为3秒
}
public String getValue(String key)
{
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
return ops.get(key);
}
}
RedisTemplate和StringRedisTemplate都是可以访问Redis数据库,区别在于
RedisTemplate使用的是JdkSerializationRedisSerializer,RedisTemplate使用的序列类在在操作数据的时候,比如说存入数据会将数据先序列化成字节数组。然后在存入Redis数据库,这个时候打开Redis查看的时候,你会看到你的数据不是以可读的形式展现的,而是以字节数组显示。
StringRedisTemplate使用的是StringRedisSerializer,Redis获取数据的时候也会默认将数据当做字节数组转化,这样就会导致一个问题,当需要获取的数据不是以字节数组存在redis当中而是正常的可读的字符串。