首页 > 数据库 >springboot缓存之整合redis

springboot缓存之整合redis

时间:2022-11-30 19:36:36浏览次数:40  
标签:engine 缓存 java springboot support redis platform org junit


 

一\引入redis

springboot缓存之整合redis_redis

springboot缓存之整合redis_java_02

springboot缓存之整合redis_spring_03

springboot缓存之整合redis_redis_04

pom.xml中添加

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

二\application.properties中写入

spring.redis.host=192.168.3.18 #redis地址(虚拟机)

打开RedisAutoConfiguration可以看到

@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}

@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}

@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

三\运行redis

springboot缓存之整合redis_java_05

四\使用测试类进行测试

package com.example.springdatacache;

import com.example.springdatacache.bean.Employee;
import com.example.springdatacache.mapper.EmployeeMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class SpringdataCacheApplicationTests {

@Autowired
EmployeeMapper employeeMapper;

@Autowired
StringRedisTemplate stringRedisTemplate; //操作k-v都是字符串的

@Autowired
RedisTemplate redisTemplate; //k-v都是对象的

/**
* Redis常见的五大数据类型
* String(字符串) ,List(列表) ,Set(集合) ,Hash(散列) ,ZSet(有序集合)
* stringRedisTemplate.opsForValue() 缓存String(字符串)
* stringRedisTemplate.opsForList() 缓存List(列表)
* stringRedisTemplate.opsForSet() 缓存Set(集合)
* stringRedisTemplate.opsForHash() 缓存Hash(散列)
* stringRedisTemplate.opsForZSet() 缓存ZSet(有序集合)
*/
@Test
public void test01(){
//给redis中保存数据
stringRedisTemplate.opsForValue().append("msg","1999999");
}

//测试保存对象
@Test
public void test02(){
Employee empById = employeeMapper.getEmpById(1);
redisTemplate.opsForValue().set("emp-01",empById);
}

@Test
void contextLoads() {
Employee empById = employeeMapper.getEmpById(1);
System.out.println(empById);
}

}

 

org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.example.springdatacache.bean.Employee]

at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:96)
at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:127)
at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:235)
at com.example.springdatacache.SpringdataCacheApplicationTests.test02(SpringdataCacheApplicationTests.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.example.springdatacache.bean.Employee]
at org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:68)
at org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:35)
at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:94)
... 66 more
Caused by: java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.example.springdatacache.bean.Employee]
at org.springframework.core.serializer.DefaultSerializer.serialize(DefaultSerializer.java:43)
at org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:63)
... 68 more

springboot缓存之整合redis_java_06

修改javabean  Employee类:


import java.io.Serializable;

public class Employee implements Serializable {


此时依然出现问题:


默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中 解决方法: 1-将数据以json的方式保存 (1)自己将对象转为json (2)redisTemplate默认的序列化规则,改变默认的序列化规则


进入RedisTemplate类,发现一系列序列化器

springboot缓存之整合redis_redis_07

springboot缓存之整合redis_redis_08

进入RedisSerializer类

ctrl+H

springboot缓存之整合redis_redis_09

五\新建config包MyRedisConfig类

进入RedisAutoConfiguration类中复制

@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}

编写: 

package com.example.springdatacache.config;

import com.example.springdatacache.bean.Employee;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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 MyRedisConfig {
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> employeeJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(employeeJackson2JsonRedisSerializer);
return template;
}
}

六\修改测试类

           新增

@Autowired
RedisTemplate<Object,Employee> empRedisTemplate;

           修改

//测试保存对象
@Test
public void test02(){
Employee empById = employeeMapper.getEmpById(1);
empRedisTemplate.opsForValue().set("emp-01",empById);
}

springboot缓存之整合redis_spring_10

标签:engine,缓存,java,springboot,support,redis,platform,org,junit
From: https://blog.51cto.com/u_12528551/5900316

相关文章

  • springboot分布式之duddo简介+docker安装zookeeper
    dubbo:解决服务之间远程服务调用问题================================================================================================1-安装zookeeperdockerpullzoo......
  • springboot热部署之devtools开发热部署
    example: 修改接口此时target/classes中的文件依然是ctrl+F9后,target/class中的文件虽然做出修改,但是并未部署到浏览器中进入spring官网的springboot官方文档中的usings......
  • springboot检索之elasticsearch快速使用
    打开elasticsearch官网,docs,简体中文->Elasticsearch:权威指南   Elasticsearch是 面向文档 的,意味着它存储整个对象或 文档。Elasticsearch不仅存储文档,而且 ......
  • SpringBoot参数校验
    1.前言因为网络传输的不可靠性,以及前端数据控制的可篡改性,后端的参数校验是必须的,应用程序必须通过某种手段来确保输入进来的数据从语义上来讲是正确的。2.数据校验的......
  • SpringBoot整合ElasticSearch
    目录1SpringBoot整合ElasticSearch1.1pom.xml1.2创建高级客户端1.3基本用法1.3.1创建、判断存在、删除索引1.3.2对文档的CRUD1.3.3批量CRUD数据1.3.4查询所有、模......
  • springboot任务之异步任务
    1-新建工程,只选web模块2-新增service包,AsyncService类packagecom.example.springboottask.service;importorg.springframework.stereotype.Service;@Servicepublicclas......
  • springcloud之springboot自动装载
        ImportSelector接口是Spring导入外部配置的核心接口,在SpringBoot的自动配置和@EnableXXX(功能性注解)中起到了决定性的作用.当在@Configuration标注的Class......
  • springboot消息之使用RabbitTemplate给rabbitmq发送和接收消息&序列化机制
    1-引入spring-boot-starter-amqp2-application.yml配置3-测试RabbitMQ  1--AmqpAdmin:管理组件  2--RabbitTemplate:消息发送处理组件======================......
  • springboot消息之@RabbitListener&@EnableRabbit监听消息队列的内容
    1-新建service包BookService类packagecom.example.springbootamqp.service;importcom.example.springbootamqp.bean.Book;importorg.springframework.amqp.rabbit......
  • springboot消息之JMS&AMQP简介
    大多应用中,可通过消息服务中间件来提升系统异步通信`扩展解耦能力.    异步处理  应用解耦  流量削峰消息服务中有两个重要概念:消息代理和目的地(m......