在CentOS下使用Docker安装Redis+Spring Boot整合Redis

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

六、可以使用RedisDesktopManager客户端连接redis具体操作不再详细说明

Spring boot 整合 redis

一、添加依赖

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

二、配置yml文件

spring:
  profiles:
    active: 8080

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=CONVERT_TO_NULL
    username: root
    password: root

  redis:
    #redis端口号
    port: 
    #服务器地址
    host: 
    #密码
    password:
    #数据库索引默认0 一共有16个数据库
    database: 0

#整合mybatis
mybatis:
  typeAliasesPackage: com.zzb.springboot_redis.pojo
  mapperLocations: classpath:mapper/*.xml
  configuration:
    auto-mapping-behavior: full

#打印sql语句
logging:
  level:
    com.zzb.springboot_redis.mapper.*: debug
debug: true

三、启动类中加入注解

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

四、加入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;
    }
}

实体类中需要实现Serializable
mapper接口

public interface StudentMapper {

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

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

    /**
     * 根据编号删除
     * @param id
     * @return
     */
    @Delete("delete from student where id = #{id}")
    int delById(Integer id);

    /**
     * 修改
     * @param student
     * @return
     */
    @Update("UPDATE student SET name = #{name}, sex = #{sex}, gradeId = #{gradeId} WHERE id = #{id}")
    int modify(Student student);
}

Service

public interface StudentService {

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

    /**
     * 根据编号查询
     * @param id
     * @return
     */
    Student findById(Integer id);

    /**
     * 根据编号删除
     * @param id
     * @return
     */
    int delById(Integer id);

    /**
     * 修改
     * @param student
     * @return
     */
    Student modify(Student student);
}

实现类

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Student> findAll() {
        String key = "students";
        ListOperations<String, Student> operations = this.redisTemplate.opsForList();
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            return operations.range(key, 0, -1);
        } else {
            List<Student> studentList = studentMapper.findAll();
            operations.leftPushAll(key, studentList);
            return studentList;
        }
    }

    /**
     * 根据编号查询
     * @param id
     * @return
     */
    @Override
    public Student findById(Integer id) {
        String key = "student" + id;
        ValueOperations<String, Student> operations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)) {
            Student student = operations.get(key);
            return student;
        }
        Student student = studentMapper.findById(id);
        operations.set(key, student);
        return student;
    }

    /**
     * 根据编号删除
     * @param id
     * @return
     */
    @Override
    public int delById(Integer id) {
        String key = "student" + id;
        studentMapper.delById(id);
        if (redisTemplate.hasKey(key)) {
            redisTemplate.delete(key);
        }
        return 1;
    }

    /**
     * 修改
     * @param student
     * @return
     */
    @Override
    public Student modify(Student student) {
        String key = "student" + student.getId();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        studentMapper.modify(student);
        if (redisTemplate.hasKey(key)){
            valueOperations.set(key,student);
        }
        return student;
    }
}

控制层

@RestController
public class StudentController {

    @Autowired
    StudentService studentService;

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

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

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

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

}

第一次查询的时候会从数据库取数据下一次就会从redis中去取了

你可能感兴趣的:(redis)