温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

讲解springboot连接Redis的教程

发布时间:2021-03-04 15:34:16 来源:亿速云 阅读:146 作者:TREX 栏目:开发技术

这篇文章主要介绍“讲解springboot连接Redis的教程”,在日常操作中,相信很多人在讲解springboot连接Redis的教程问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”讲解springboot连接Redis的教程”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

创建springboot项目

讲解springboot连接Redis的教程
讲解springboot连接Redis的教程

NoSQL中选择Redis

讲解springboot连接Redis的教程
讲解springboot连接Redis的教程

项目目录

讲解springboot连接Redis的教程

pom.xml中还需要加入下面的jar包

org.springframework.boot spring-boot-starter-json

application.properties文件中添加Redis服务器信息

spring.redis.host=192.168.5.132
spring.redis.port=6379

剩下4个test类,我直接以源码的方式粘出来,里面有些代码是非必须的,我保留了测试的验证过程,所以里面会有冗余代码。(这些代码在我GitHub上的练习项目中也有)

package com.myspringboot.redis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(DemoApplication.class, args);
    RedisTest redisTest = configurableApplicationContext.getBean(RedisTest.class);
    redisTest.testRedis();
  }

}
package com.myspringboot.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

@Configuration
public class MyTemplate {

  @Bean
  public StringRedisTemplate getMyTemplate(RedisConnectionFactory redisConnectionFactory){
    StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(redisConnectionFactory);
    stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
    return stringRedisTemplate;
  }
}
package com.myspringboot.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.hash.Jackson2HashMapper;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RedisTest {

  @Autowired
  RedisTemplate redisTemplate;


  @Autowired
  StringRedisTemplate stringRedisTemplate;

  @Autowired
  ObjectMapper objectMapper;

  // 自定义模板
  @Autowired
  @Qualifier("getMyTemplate")
  StringRedisTemplate myStringRedisTemplate;

  public void testRedis()  {
    //redis中直接查看时,乱码
    redisTemplate.opsForValue().set("key1", "hello1");
    System.out.println(redisTemplate.opsForValue().get("key1"));

    //redis中直接查看时,正常
    stringRedisTemplate.opsForValue().set("key2", "hello2");
    System.out.println(stringRedisTemplate.opsForValue().get("key2"));

    RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
    connection.set("key3".getBytes(), "hello3".getBytes());
    System.out.println(new String(connection.get("key3".getBytes())));

    HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();
    hash.put("key4", "name", "张三");
    hash.put("key4", "age", "18");
    System.out.println(hash.get("key4", "name"));
    System.out.println(hash.entries("key4"));


    stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
    Jackson2HashMapper jackson2HashMapper = new Jackson2HashMapper(objectMapper, false);// true 扁平化(将对象中的参数展开)
    User user = new User();
    user.setId(123);
    user.setName("zhangsan");
    stringRedisTemplate.opsForHash().putAll("key5", jackson2HashMapper.toHash(user));
    Map map = stringRedisTemplate.opsForHash().entries("key5");
    User user1 = objectMapper.convertValue(map, User.class);
    System.out.println(user1.getId());
    System.out.println(user1.getName());


    myStringRedisTemplate.opsForHash().putAll("key6", jackson2HashMapper.toHash(user));
    Map map1 = myStringRedisTemplate.opsForHash().entries("key6");
    User user2 = objectMapper.convertValue(map, User.class);
    System.out.println(user2.getId());
    System.out.println(user2.getName());


    //发布订阅
    myStringRedisTemplate.convertAndSend("qunliao", "hello");

    RedisConnection connection1 = myStringRedisTemplate.getConnectionFactory().getConnection();
    connection1.subscribe(new MessageListener() {
      @Override
      public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        System.out.println(new String(body));
      }
    }, "qunliao".getBytes());


    while (true){
      myStringRedisTemplate.convertAndSend("qunliao", "hello");
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
package com.myspringboot.redis;

public class User {
  private int id;
  private String name;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

到此,关于“讲解springboot连接Redis的教程”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI