微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

springboot使用redisTemplate

第一步:创建spring boot项目导入redis相关依赖

 <!-- spring data redis 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- commons-pool2 对象池依赖 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

第二步:在application.yml中编写redis相关配置

srping:                     
  redis:
      # 超时时间
      timeout: 10000ms
      # 服务器地址
      host: 192.168.4.13
      # 服务器端口
      port: 6379
      # 数据库
      database: 0
      # 密码
      # password: root
      lettuce:
        pool:
          # 最大连接数
          max-active: 1024
          # 最大连接阻塞等待时间
          max-wait: 10000ms
          # 最大空闲连接
          max-idle: 200
          # 最小空闲连接
          min-idle: 5

第三步:编写redistemplate的配置类

@Configuration
public class RedisConfig {

    @Bean
    public Redistemplate<String,Object> redistemplate(RedisConnectionFactory redisConnectionFactory){
        Redistemplate<String,Object> redistemplate = new Redistemplate<>();
        //key序列化
        redistemplate.setKeySerializer(new StringRedisSerializer());
        //value序列化
        redistemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //hash类型key序列化
        redistemplate.setHashKeySerializer(new StringRedisSerializer());
        //hash类型value序列化
        redistemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //注入连接工厂
        redistemplate.setConnectionFactory(redisConnectionFactory);
        return redistemplate;
    }
}

第四步:让实体类实现序列化

//序列化接口Serializable 
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 用户ID,手机号码
     */
    private Long id;

    /**
     * 用户名
     */
    private String nickname;

    /**
     * MD5(MD5(明文+固定salt)+salt)
     */
    private String password;

    private String slat;
    /**
     * 头像
     */
    private String head;

    /**
     * 注册时间
     */
    private Date registerDate;

    /**
     * 注册时间
     */
    private Date lastLoginDate;

    /**
     * 登入次数
     */
    private Integer loginCount;


}

第五步:使用redistemplate往redis存放数据

@Autowired
    private Redistemplate redistemplate;
redistemplate.opsForValue().set("user:"+ticket,user);

在这里插入图片描述

完成!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐