springboot整合redis

redis的默认端口号为6379

1.添加依赖

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

2.添加到redis 里的数据为二进制需要需要序列化(转化为json格式)需要添加配置类

package com.zzq.springboot_redis.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.Jackson2JsonRedisSerializer;

import java.net.UnknownHostException;
@Configuration
public class Config {


        @Bean
        public RedisTemplate<Object, Object> redisTemplate(
                RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

            RedisTemplate<Object, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory);
            //修改默认的序列化规则
            //1.创建序列化规则对象
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
            //2.更改默认的序列化规则
            template.setDefaultSerializer(jackson2JsonRedisSerializer);
            return template;
        }
}

3.实体类需 implements Serializable

4.实现类

 @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Student> getAll() {
        String key = "student";
        ListOperations<String, Student> listOperations = redisTemplate.opsForList();
        Boolean aBoolean = redisTemplate.hasKey(key);
        if (aBoolean) {
            return listOperations.range(key, 0, -1);
        } else {
            List<Student> all = studentMapper.getAll();
            listOperations.leftPushAll(key, all);
            return all;
        }

5.控制层

  @GetMapping("/students")
  public List<Student> getAll(){
      return studentServiece.getAll();
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值