溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

講解springboot連接Redis的教程

發(fā)布時(shí)間:2021-03-04 15:34:16 來(lái)源:億速云 閱讀:151 作者:TREX 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“講解springboot連接Redis的教程”,在日常操作中,相信很多人在講解springboot連接Redis的教程問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”講解springboot連接Redis的教程”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

創(chuàng)建springboot項(xiàng)目

講解springboot連接Redis的教程
講解springboot連接Redis的教程

NoSQL中選擇Redis

講解springboot連接Redis的教程
講解springboot連接Redis的教程

項(xiàng)目目錄

講解springboot連接Redis的教程

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

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

application.properties文件中添加Redis服務(wù)器信息

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

剩下4個(gè)test類(lèi),我直接以源碼的方式粘出來(lái),里面有些代碼是非必須的,我保留了測(cè)試的驗(yàn)證過(guò)程,所以里面會(huì)有冗余代碼。(這些代碼在我GitHub上的練習(xí)項(xiàng)目中也有)

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中直接查看時(shí),亂碼
    redisTemplate.opsForValue().set("key1", "hello1");
    System.out.println(redisTemplate.opsForValue().get("key1"));

    //redis中直接查看時(shí),正常
    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 扁平化(將對(duì)象中的參數(shù)展開(kāi))
    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());


    //發(fā)布訂閱
    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;
  }
}

到此,關(guān)于“講解springboot連接Redis的教程”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI