Docker 安装 Redis + Spring Boot 整合 Redis

Docker安装Redis

一、启动docker容器

systemctl start docker

二、拉取redis镜像

docker pull redis

三、端口映射

docker run --name redis -p 6379:6379 -d redis

四、启动redis

docker start redis

五、查询ip

ip addr

六、连接redis
Docker 安装 Redis + Spring Boot 整合 Redis_第1张图片

Spring boot 整合 redis

一、添加依赖

	<dependency>
           <groupId>org.springframework.bootgroupId>
           <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>

二、配置yml文件

server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root

  redis:
    host: #此处应填写服务器ip 通过上述命令 ip addr 可查看
    #redis端口
    port: 6379
    # Redis数据库索引(默认为0) 密码之类的 默认是没有的可以写
    database: 0

# 打印SQL语句
logging:
  level:
  	#改为自己的mapper包路径
    com.nebula.springboot_redis.mapper: debug

三、启动类中加入注解

@MapperScan(value = "com.nebula.springboot_redis.mapper") //指定要扫描的mapper包路径

@SpringBootApplication
public class SpringbootRedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedisApplication.class, args);
    }

}

项目结构如下:
Docker 安装 Redis + Spring Boot 整合 Redis_第2张图片

四、加入RedisConfig文件

@Configuration
public class RedisConfig {
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}


实体类
@Data
public class Student implements Serializable {

    //编号
    private Integer id;

    //姓名
    private String name;

    //性别
    private String sex;

}

Mapper
@Mapper
public interface StudentMapper {

    /**
     * 查询所有
     *
     * @return
     */
    @Select("select * from student")
    List<Student> findAll();

    /**
     * 根据id查询学生信息
     *
     * @param id id
     * @return
     */
    @Select("select * from student where id=#{id}")
    Student findById(Integer id);

    /**
     * 根据id删除学生信息
     *
     * @param id id
     * @return
     */
    @Delete("delete from student where id =#{id}")
    int del(Integer id);

    /**
     * 修改学生信息
     *
     * @param student
     * @return
     */
    @Update("update student set name =#{name},sex=#{sex} where id=#{id}")
    int modify(Student student);

}

Service
public interface StudentService {

    /**
     * 查询所有
     *
     * @return
     */
    List<Student> findAll();

    /**
     * 根据id查询学生信息
     *
     * @param id id
     * @return
     */
    Student findById(Integer id);


    /**
     * 根据id删除学生信息
     *
     * @param id id
     * @return
     */
    int del(Integer id);

    /**
     * 修改学生信息
     *
     * @param student
     * @return
     */
    int modify(Student student);
}

实现层
@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    StudentMapper studentMapper;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<Student> findAll() {
        String key = "student";
        ListOperations<String, Student> operations = redisTemplate.opsForList();

        //缓存存在
        if (redisTemplate.hasKey(key)) {
            return operations.range(key, 0, -1);
        } else {
            //得到学生集合
            List<Student> list = studentMapper.findAll();
            operations.leftPushAll(key, list);
            return list;
        }
    }

    /**
     * 根据id查询学生信息
     *
     * @param id id
     * @return
     */
    @Override
    public Student findById(Integer id) {
        String key = "student_" + id;
        ValueOperations<String, Student> operations = redisTemplate.opsForValue();

        //缓存存在
        if (redisTemplate.hasKey(key)) {
            return operations.get(key);
        } else {
            //得到学生对象
            Student student = studentMapper.findById(id);
            //添加到缓存
            operations.set(key, student);
            return student;
        }
    }


    /**
     * 根据id删除学生信息
     *
     * @param id id
     * @return
     */
    @Override
    public int del(Integer id) {
        //删除数据库中的数据
        int count = studentMapper.del(id);

        //缓存存在
        String key = "student_" + id;
        if (redisTemplate.hasKey(key)) {
            //删除对应缓存
            redisTemplate.delete(key);
        }
        return count;
    }

    /**
     * 修改学生信息
     *
     * @param student
     * @return
     */
    @Override
    public int modify(Student student) {
        //修改数据库中的数据
        int count = studentMapper.modify(student);

        ValueOperations operations = redisTemplate.opsForValue();
        //缓存存在
        String key = "student_" + student.getId();
        if (redisTemplate.hasKey(key)) {
            //更新缓存
            Student stu = studentMapper.findById(student.getId());
            operations.set(key, stu);
        }
        return count;
    }
}


控制层
@RestController
public class StudentController {

    @Resource
    StudentService studentService;

    @GetMapping("/student")
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @GetMapping("/student/{id}")
    public Student findById(@PathVariable("id") Integer id) {
        return studentService.findById(id);
    }

    @PostMapping("/student/{id}")
    public int del(@PathVariable("id") Integer id) {
        return studentService.del(id);
    }

    @PutMapping("/student")
    public int modify(Student student) {
        return studentService.modify(student);
    }

}

运行,使用 Postman 请求查询所有方法
Docker 安装 Redis + Spring Boot 整合 Redis_第3张图片
请求了一次数据库

查看 Redis 可视化工具
Docker 安装 Redis + Spring Boot 整合 Redis_第4张图片
完成!!!下次再查询所有时将无需再重新请求数据库,而是直接从缓存中取数据。

你可能感兴趣的:(spring,boot)