springboot2.x使用redis作为缓存,自定义序列化和反序列化

本文探讨SpringBoot2.x与1.x在整合Redis缓存时的区别,特别是RedisCacheManager的变化。通过配置application.properties,自定义序列化和反序列化方式,实现高效的数据存储和读取。涉及领域包括domain、mapper、service、controller,并提供了测试类以验证配置的正确性。
摘要由CSDN通过智能技术生成
SpringBoot2.x和1.x的区别很大,比如在整合 Redis 这一块,RedisCacheManager就有不同。

application.properties

# database name
spring.redis.database=0
# server host1
# spring.redis.host=127.0.0.1
spring.redis.host=47.112.4.110
# server password
# spring.redis.password=123456
spring.redis.password=
#connection port
spring.redis.port=6379
# pool settings ...
spring.redis.jedis.pool.max-idle=8 
spring.redis.jedis.pool.min-idle=0
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1

redis配置类:(最重要的的是配置类)

@Configuration
@EnableCaching
public class redisConf {
    //过期时间30秒
    private Duration timeToLive = Duration.ofSeconds(30L);
    Logger log= LoggerFactory.getLogger(getClass());
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //默认1
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
        log.debug("自定义RedisCacheManager加载完成");
        return redisCacheManager;
    }
    @Bean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
        log.debug("自定义RedisTemplate加载完成");
        return redisTemplate;
    }
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}

domain

public class Department implements Serializable {

    private Integer id;
    private String departmentName;

    public void setId(Integer id) {
        this.id = id;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public Integer getId() {
        return id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", departmentName='" + departmentName + '\'' +
                '}';
    }
}

mapper


@Mapper
public interface departmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);

}

service

@Service
public class departmentService implements IdepartmentService{

    @Autowired
    departmentMapper departmentMapper;

    @Cacheable(cacheNames = "dept", unless = "#result == null ")
    public Department getDeptById(Integer id){
        System.out.println("查询部门"+id);
        Department department = departmentMapper.getDeptById(id);
        return department;
    }
}

controller

@RestController
public class departmentController {

    @Autowired
    departmentService departmentService;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable(value = "id") Integer id){

        //return departmentService.getBYid(id);
        return  departmentService.getDeptById(id);
    }
}

测试类

@SpringBootTest
class DemodruidApplicationTests {
   

    @Autowired
    StringRedisTemplate stringRedisTemplate;  //操作k-v都是字符串的
    @Autowired
    RedisTemplate redisTemplate;  //k-v都是对象的
    @Autowired
    EmployeeService employeeService;
    @Autowired
    departmentService departmentService;

    /**
     * Redis常见的五大数据类型
     *  String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
     *  stringRedisTemplate.opsForValue()[String(字符串)]
     *  stringRedisTemplate.opsForList()[List(列表)]
     *  stringRedisTemplate.opsForSet()[Set(集合)]
     *  stringRedisTemplate.opsForHash()[Hash(散列)]
     *  stringRedisTemplate.opsForZSet()[ZSet(有序集合)]
     */
    @Test
    public void test01(){
   
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值