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 = new GenericFastJsonRedisSerializer();
redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}