可以直接导入Jedis框架,它能够实现Java与Redis数据库的交互
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
public static void main(String[] args) {
//创建Jedis对象
Jedis jedis = new Jedis("localhost", 6379);
//使用之后关闭连接
jedis.close();
}
jedis的方法与redis的命令基本相同,如果想执行redis命令只需执行相应的方法
public static void main(String[] args) {
try(Jedis jedis = new Jedis("localhost", 6379)){
jedis.hset("person", "name", "sxc"); //等同于 hset hhh name sxc
jedis.hset("person", "sex", "19"); //等同于 hset hhh age 19
jedis.hgetAll("hhh").forEach((k, v) -> System.out.println(k+": "+v));
}
}
SpringBoot整合Redis
导入相应的starter,它底层没有用Jedis,而是Lettuce
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
starter提供的默认配置会去连接本地的Redis服务器,并使用0号数据库,可以手动进行修改配置
spring:
redis:
#Redis服务器地址
host: localhost
#端口
port: 6379
#使用几号数据库
database: 0
starter已经提供了两个默认的模板类,StringRedisTemplate和RedisTemplate<Object, Object>
可以直接注入StringRedisTemplate
来使用模板
@Resource
StringRedisTemplate template;
@Test
public void contextLoads() {
Set<String> keys = template.keys("*");
assert keys != null;
keys.forEach(System.out::println);
}
由于Spring没有专门的Redis事务管理器,但可以用JDBC提供的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
@Service
public class RedisService {
@Resource
StringRedisTemplate template;
@PostConstruct
public void init(){
template.setEnableTransactionSupport(true); //需要开启事务
}
@Transactional //需要添加此注解
public void test(){
template.multi();
template.opsForValue().set("a", "1");
template.exec();
}
}
序列化存储对象时注意要实现Serializable接口
也可以为RedisTemplate对象配置一个Serializer来实现对象的JSON存储,要导入jackson-bind包
//注意Student需要实现序列化接口才能存入Redis
template.opsForValue().set("student", new Student());
System.out.println(template.opsForValue().get("student"));