102.【Redis】(六)

简介: 102.【Redis】

2.源码分析

@AutoConfiguration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
  @Bean
  //默认的redisTemplate 没有过多的设置,redis对象都是需要序列化。
  @ConditionalOnMissingBean(name = "redisTemplate")  //我们可以自定义一个redisTemlate来替换这个默认的。
  @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
  // 两个泛型都是Object 的类型,我们后面使用的话需要强制转化
  public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
  }
  @Bean
  @ConditionalOnMissingBean
  @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
  public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    return new StringRedisTemplate(redisConnectionFactory);
  }
}

可以配置的参数

@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
  /**
   * Database index used by the connection factory.
   */
  private int database = 0;
  /**
   * Connection URL. Overrides host, port, and password. User is ignored. Example:
   * redis://user:password@example.com:6379
   */
  private String url;
  /**
   * Redis server host.
   */
  private String host = "localhost";
  /**
   * Login username of the redis server.
   */
  private String username;
  /**
   * Login password of the redis server.
   */
  private String password;
  /**
   * Redis server port.
   */
  private int port = 6379;
  /**
   * Whether to enable SSL support.
   */
  private boolean ssl;
  /**
   * Read timeout.
   */
  private Duration timeout;
  /**
   * Connection timeout.
   */
  private Duration connectTimeout;
  /**
   * Client name to be set on connections with CLIENT SETNAME.
   */
  private String clientName;
  /**
   * Type of client to use. By default, auto-detected according to the classpath.
   */
  private ClientType clientType;
  private Sentinel sentinel;
  private Cluster cluster;

3.导入配置链接

application.properties

# 链接远程主机
spring.redis.host=IP
#端口
spring.redis.port=6379
#密码
spring.redis.password=*****

4.测试

package com.jsxs;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
@SpringBootTest
class Redis02SpringBootApplicationTests {
    @Resource
    RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        //  redisTemplate-》操作不同的类型
        //  操作字符串opsForValue()
        //  操作List opsForList()
        //  操作SET  opsForSet()
        //  操作Hash opsForHash()
        //  操作地图  opsForGeo()
        // 除了基本的操作,我们常用的方法都可以直接redisTemplate来调用,比如事务和基本的增删改查。
//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();    获取链接对象
        redisTemplate.opsForValue().set("myKey","jsxs");
        System.out.println(redisTemplate.opsForValue().get("myKey"));
    }
}

5.设置中文乱码问题展现💥

如果设置中文的话,在控制无误,但是会在redis-cli出错

以下是序列化配置

(九)、自定义RedisTemplate

1.对象通过json传入

在企业开发中,对象都是先转换为json字符串再进行传递

@Test
    void test() throws JsonProcessingException {
        // 真实开发一般都是使用json来传递对象
        User user = new User("吉士先生", 22);
        // 将一个对象转换为json字符串的
        String jsonUser = new ObjectMapper().writeValueAsString(user);
        redisTemplate.opsForValue().set("user", jsonUser);
        System.out.println(redisTemplate.opsForValue().get("user"));
    }

2.直接传递一个对象

假如我们直接传一个对象就会报错: 没有序列化

进行序列化之后。

在企业中,我们所有的pojo都会序列化

package com.jsxs.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private String name;
    private int age;
}

3.解决中文乱码问题 💥

我们在config中添加这个配置

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.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        // 将template 泛型设置为 <String, Object>
        RedisTemplate<String, Object> template = new RedisTemplate();
        // 连接工厂,不必修改
        template.setConnectionFactory(redisConnectionFactory);
        /*
         * 序列化设置
         */
        // key、hash的key 采用 String序列化方式
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // value、hash的value 采用 Jackson 序列化方式
        template.setValueSerializer(RedisSerializer.json());
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();
        return template;
    }
}

测试类一定要指向redisTemplate

package com.jsxs;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsxs.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
@SpringBootTest
class Redis02SpringBootApplicationTests {
    @Resource
    @Qualifier("redisTemplate")  //指向配置类
    RedisTemplate redisTemplate;
    @Test
    void test() throws JsonProcessingException {
        // 真实开发一般都是使用json来传递对象
        User user = new User("吉士先生", 22);
        // 将一个对象转换为json字符串的
        String jsonUser = new ObjectMapper().writeValueAsString(user);
        redisTemplate.opsForValue().set("user", user);
        System.out.println(redisTemplate.opsForValue().get("user"));
    }
}

相关文章
|
Linux 测试技术 Docker
Linux系统:第十三章:centos误删文件如何恢复文件数据
Linux系统:第十三章:centos误删文件如何恢复文件数据
1004 0
Linux系统:第十三章:centos误删文件如何恢复文件数据
|
12月前
|
网络安全
IP地址SSL证书怎么申请?
本文介绍如何申请浏览器及系统可信的SSL证书,而非自签名证书。申请IP地址SSL证书需满足:1. 使用公网IP;2. 确保外网可访问;3. 认证时必须使用80或443端口。流程包括提交申请、建立临时站点验证URL内容,认证通过后即可获取证书文件,适用于各种服务器环境。若申请多个IP地址,建议一次性提交以避免串站问题。
475 6
|
机器学习/深度学习 人工智能 自然语言处理
BERT的继任者ModernBERT:融合长序列处理、代码理解与高效计算的新一代双向编码器
ModernBERT 是一个全新的模型系列,在**速度**和**准确性**两个维度上全面超越了 BERT 及其后继模型。
840 9
|
前端开发 图形学 开发者
【独家揭秘】那些让你的游戏瞬间鲜活起来的Unity UI动画技巧:从零开始打造动态按钮,提升玩家交互体验的绝招大公开!
【9月更文挑战第1天】在游戏开发领域,Unity 是最受欢迎的游戏引擎之一,其强大的跨平台发布能力和丰富的功能集让开发者能够迅速打造出高质量的游戏。优秀的 UI 设计对于游戏至关重要,尤其是在手游市场,出色的 UI 能给玩家留下深刻的第一印象。Unity 的 UGUI 系统提供了一整套解决方案,包括 Canvas、Image 和 Button 等组件,支持添加各种动画效果。
1013 3
|
机器学习/深度学习 人工智能 算法
人工智能之从零理解人工神经网络
人工智能并非是一个新型的词汇,从十九世纪五十年代开始,人们就开始探索为机器赋予类似人的智能能力。限于当时的基础数学理论不够完善,人工智能的发展并不顺利。直到九十年代发展出了基于统计学的数学工具,人工智能才得到飞速的发展。
363 5
人工智能之从零理解人工神经网络
|
Oracle Java 关系型数据库
为啥叫Java呢?Java的命名
为啥叫Java呢?Java的命名
351 1
|
消息中间件 缓存 Java
【RocketMq】NameServ启动脚本分析(Ver4.9.4)
【RocketMq】NameServ启动脚本分析(Ver4.9.4)
302 0
|
Web App开发 缓存 网络协议
POST与GET的区别深度比较分析
HTTP定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE。
708 0