SSM整合Redis

本文介绍了如何在Spring Boot项目中整合Redis,包括添加Redis依赖、配置Redis连接参数,以及如何处理序列化问题。默认使用JDK序列化可能导致乱码,文章提供了配置FastJsonRedisSerializer作为序列化方式的示例。
摘要由CSDN通过智能技术生成

1.介绍前补充说明

1.使用redis,在RedisTemplate中已经封装增删改查操作,直接调用
2.redis配置序列化方式,默认JDK序列化存储会乱码

2.整合流程

1.添加redis依赖
2.在yml或application.properties中配置redis  ip,端口,数据库等
3.配置redis序列化(可不配置 在redis数据库中显示的代码是乱码)

2.1 添加redis依赖

        <!--redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.2在yml或者application.properties中配置redis

#redis
spring.redis.host=127.0.0.1(主机或服务器ip)
spring.redis.port=6379(端口)
spring.redis.database=3 (选择的数据库)
spring.redis.password=123(redis密码)

2.3 不进行序列化配置直接使用redis


    @Override
    public propImproEntity selectListInfo(int id) {
        int a= 1;
        redisTemplate.opsForValue().set(1,a);
      return propImproDao.selectListInfo(id);
    }


不进行序列化配置

2.4 不使用默认的jdk序列化,配置其他的序列化

package com.example.sdv.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.cache.annotation.EnableCaching;
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.GenericToStringSerializer;

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用 GenericFastJsonRedisSerializer 替换默认序列化
        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        // 设置key和value的序列化规则
        redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
        redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
        // 设置hashKey和hashValue的序列化规则
        redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
        redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
        // 设置支持事物
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;


    }
}

使用序列化配置

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值