可以直接导入Jedis框架,它能够实现Java与Redis数据库的交互
redis.clients
<artifactId>jedis
4.0.0
- 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));
- }
- }
导入相应的starter,它底层没有用Jedis,而是Lettuce
org.springframework.boot
spring-boot-starter-data-redis
starter提供的默认配置会去连接本地的Redis服务器,并使用0号数据库,可以手动进行修改配置
spring:
redis:
#Redis服务器地址
host: localhost
#端口
port: 6379
#使用几号数据库
database: 0
starter已经提供了两个默认的模板类,StringRedisTemplate和RedisTemplate
可以直接注入StringRedisTemplate来使用模板
- @Resource
- StringRedisTemplate template;
- @Test
- public void contextLoads() {
- Set
keys = template.keys("*"); - assert keys != null;
- keys.forEach(System.out::println);
- }
由于Spring没有专门的Redis事务管理器,但可以用JDBC提供的
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
- @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"));