Springboot整合Redis自定义对象序列化

分类专栏:
Redis

文章标签:
Java自学
Redis
原创

1.创建一个SpringBoot项目,pom文件中引入相关依赖

		<dependencies>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
        
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.3</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <scope>provided</scope>
		</dependency>

		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-devtools</artifactId>
		</dependency>
		
	</dependencies>

2.准备环境及创建测试所需要的类

yml文件:
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cache
    username: root
    password: xxxx(数据库密码)
  redis:
    host: xxxxxxx(自己redis安装的服务器ip地址)
    port: 6379
    password: xxxxx(redis密码)
    
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations:
  - classpath:mybatis/mapper/*.xml
  
debug: true
    
SQL文件:
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_id` int(11) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

LOCK TABLES `employee` WRITE;
INSERT INTO `employee` VALUES (1,1,'zhangsan@qq.com','zhangsan',20),(2,1,'lisi@qq.com','lisi',18);
UNLOCK TABLES;

Mapper文件:
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.pz.dao.EmployeeDao">

	<resultMap type="com.pz.domain.Employee" id="BaseResult">
		<id column="id" property="id"/>
		<result column="name" property="name"/>
		<result column="age" property="age"/>
		<result column="email" property="email"/>
		<result column="dept_id" property="deptId"/>
	</resultMap>

	<select id="findAll" resultMap="BaseResult">
		select * from employee	
	</select>

</mapper>
主启动类:
@SpringBootApplication
@EnableCaching
public class SpringbootRedisApplication {

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

controller:

@RestController
public class EmployeeController {

  @Autowired private EmployeeService employeeService;

  @GetMapping("/list")
  public List<Employee> list() {
    return employeeService.findAll();
  }

  @GetMapping("/emp/{id}")
  public Employee emp(@PathVariable("id") Integer id) {
    return employeeService.selectEmp(id);
  }
}

service:
@Service
public class EmployeeService {

  @Autowired private EmployeeDao employeeDao;

  @Cacheable(cacheNames = "employee")
  public List<Employee> findAll() {
    System.out.println("查询所有员工......");
    return employeeDao.findAll();
  }

  @Cacheable(cacheNames = "employee--id")
  public Employee selectEmp(Integer id) {
    System.out.println("查询员工:" + id);
    return employeeDao.selectById(id);
  }
}

dao:
@Mapper
public interface EmployeeDao {

  List<Employee> findAll();

  @Select("SELECT * FROM employee WHERE id = #{id}")
  Employee selectById(Integer id);
}

实体类:
@Data
public class Employee implements Serializable {

  private Integer id;

  private String name;

  private String email;

  private Integer age;

  private Integer deptId;
}

配置类:
/**
 * 自定义redis配置
 */
@Configuration
public class MyRedisConfig extends CachingConfigurerSupport {

  /** 重写生成key的方法:类名+方法名+参数名 */
  @Bean
  @Override
  public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
      public Object generate(Object target, Method method, Object... objects) {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName())
            .append(".")
            .append(method.getName())
            .append(Arrays.toString(objects));
        return sb.toString();
      }
    };
  }

  @Bean
  public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
      throws UnknownHostException {
    RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
    template.setConnectionFactory(redisConnectionFactory);
    //		Jackson2JsonRedisSerializer<Object> serializer = new
    // Jackson2JsonRedisSerializer<>(Object.class);
    GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
    template.setDefaultSerializer(serializer);
    return template;
  }
}

运行主启动类,打开浏览器输入localhost:8080/emp/1或localhost:8080/emp/2

结果如下 这里 使用到了RedisDesktopManager

在这里插入图片描述 在这里插入图片描述

    // 这是RedisDesktopManager安装包
    链接:https://pan.baidu.com/s/1NLGYE6uma48WxG_nrgRK-A
    提取码:pz99 
   //安装时会报错 什么URL什么的 不用管 照常能用

博客图片来自本人CSDN

  • 作者:潘震
  • 评论

    pz
    博主
    安装时会报错,不用管照常能用
    留言