springboot整合redis-SpringBoot(22)

springboot整合redis-SpringBoot(22)

1. 在 Spring Boot 中集成 Redis

  (1)完成配置基础项。

    添加 Redis、MySQL、MyBatis 依赖。

  (2)配置MySQL、Redis服务器

    可以直接在application.yml文件中逬行配置,具体配置方法见以下代码:

查看代码

# 应用名称
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 5000
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
      username: root
      password: 123456
    thymeleaf:
      mode: HTML
      encoding: UTF-8
      servlet:
        content-type: text/html
      cache: false
      prefix: classpath:/static/

mybatis:
  # spring boot集成mybatis的方式打印sql
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 应用服务 WEB 访问端口
server:
  port: 8080

  (3)在入口类加上@EnableCaching注解,开启缓存支持。

2. 配置Redis类

  要想启用Spring缓存支持,需创建一个CacheManager的Bean

package com.intehel.demo.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.lang.reflect.Method;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //在缓存对象集合中,缓存是以key-value形式保存的
    //如果没有指定缓存的key,则Spring Boot 会使用SimpleKeyGenerator生成key
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            //定义缓存key的生成策略
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    @SuppressWarnings("rawtypes")
    @Bean
    //缓存管理器 2.X版本
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);
        return cacheManager;
    }
    //缓存管理器 1.X版本
/*    public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate){
        return new RedisCacheManager(redisTemplate);
    }*/

    @Bean
    //注册成Bean被Spring管理,如果没有这个Bean,则Redis可视化工具中的中文内容都会以二进制存储,不易检查
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

3.创建测试实体类

  创建用于数据操作的测试实体类,见以下代码:

package com.intehel.demo.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private Long id;
    private String name;
    private Integer age;
    private String address;
}

4. 实现实体和数据表的映射关系

package com.intehel.demo.mapper;

import com.intehel.demo.domain.Person;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface PersonMapper {
    @Insert("insert into person(name, age,address) values(#{name},#{age},#{address})")
    int addPerson(@Param("name")String name, @Param("age")String age, @Param("address")String address);
    @Select("select * from person where id = #{id}")
    Person findById(@Param("id")String id);
    @Update("update person set age = #{age},name = #{name},address = #{address} where id = #{id}")
    int updateById(Person person);
    @Delete("delete from person where id = #{id}")
    void deleteById(@Param("id")String id);
}

5. 创建Redis缓存服务层

package com.intehel.demo.service;

import com.intehel.demo.domain.Person;
import com.intehel.demo.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "person")
public class PersonService {
    @Autowired
    PersonMapper personMapper;
    @Cacheable(key = "#p0")
    public Person selectPerson(String id){
        System.out.println("selectPerson");
        return personMapper.findById(id);
    }
    @CachePut(key = "#p0")
    public void updatePerson(Person person){
        System.out.println("updatePerson");
        personMapper.updateById(person);
    }
    @CacheEvict(key = "#p0",allEntries = true)
    public void deletePerson(String id){
        System.out.println("deletePerson");
        personMapper.deleteById(id);}
}

代码解释如下。

  • @Cacheable:将查询结果缓存到Redis中。
  • key=”#p0″:指定传入的第1个参数作为Redis的key。
  • @CachePut:指定key, 将更新的结果同步到Redis中。
  • @CacheEvict:指定key, 删除缓存数据。
  • @allEntries=true:方法调用后将立即清除缓存

6.完成增加、删除、修改和查询测试API

package com.intehel.demo.controller;

import com.intehel.demo.service.PersonService;
import com.intehel.demo.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class PersonController {
    @Autowired
    PersonService personService;
    @RequestMapping(value = "/{id}")
    public Person selectPerson(@PathVariable String id){
        return personService.selectPerson(id);
    }
    @RequestMapping(value = "/update")
    public String updatePerson(@RequestBody Person person){
        personService.updatePerson(person);
        return "success";
    }
    @RequestMapping(value = "/delete/{id}")
    public String deletePerson(@PathVariable String id){
        personService.deletePerson(id);
        return "delete success";
    }
}

  启动项目,多次访问http://localhost:8080/user/1 第一次时控制台会出现select信息,代表对数据库进行了查询操作。后面再访问时则不会出现提示,表示没有对数据库执行操作,而是使用 Redis中的缓存数据。

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » springboot整合redis-SpringBoot(22)