首页
赞助
时间轴
追番
留言
友人帐
关于
个人导航
更多
学习笔记
壁纸
Search
1
【台式机】2020-06-07,上半年618推荐配置(都是AMD)
983 阅读
2
21年下半年笔记本挑选
940 阅读
3
域名备案成功
809 阅读
4
2020.10 手机号码正则表达式
748 阅读
5
Mybatis缓存
719 阅读
日常
代码
❤心情
博客插件
电脑推荐
KMS服务
登录
Search
标签搜索
电脑推荐
组装电脑
Mybatis
SpringBoot
博客插件
跨域访问错误
Maven
Linux
node.js
WebSocket
跨域
网页背景效果
音乐播放器
看板娘
Pio插件问题
气泡通知
轻薄本
全能本
笔记本推荐
伪静态
旧梦未眠
累计撰写
86
篇文章
累计收到
16
条评论
今日撰写
0
篇文章
首页
栏目
日常
代码
❤心情
博客插件
电脑推荐
KMS服务
页面
赞助
时间轴
追番
留言
友人帐
关于
个人导航
学习笔记
壁纸
用户登录
登录
搜索到
4
篇与
SpringBoot
的结果
2025-11-10
Spring Boot3整合MyBatisPlus实现多数据源
1.导入多数据源pom依赖<!-- 多数据源 --> <!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot3-starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot3-starter</artifactId> <version>4.3.1</version> </dependency>2.配置数据库链接spring: datasource: dynamic: #主要数据库 primary: master #严格匹配模式,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源 strict: false datasource: master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/database_1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8 username: database_1 password: database_1 type: com.zaxxer.hikari.HikariDataSource account: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/database_2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8 username: database_2 password: database_2 type: com.zaxxer.hikari.HikariDataSource charac: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/database_3?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8 username: database_3 password: database_3 type: com.zaxxer.hikari.HikariDataSource postal: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/database_4?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8 username: database_4 password: database_4 type: com.zaxxer.hikari.HikariDataSource 3.在Mapper上标注@DS比如我这个mapper是Account数据库import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.jam.entities.gameEntities.Accounts; import org.springframework.stereotype.Repository; @DS("account") @Repository public interface AccountsMapper extends BaseMapper<Accounts> { }4.在启动器标注扫描Mapper@MapperScan("com.jam.mapper.**")@SpringBootApplication @EnableCaching @MapperScan("com.jam.mapper.**") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
2025年11月10日
1 阅读
0 评论
0 点赞
2025-11-05
SpringBoot在使用@Cacheable缓存对象为空
1.情况SpringBoot在使用@Cacheable缓存对象为空具体就是在实体类的时候,List<Integer>为空1.1 实体类@Schema( description = "赠送礼物id") private List<Integer> itemId; @Schema( description = "赠送礼物数量") private List<Integer> itemNum;1.2 数据库item_id varchar(255)item_num varchar(255)1.3 Service@Cacheable(cacheNames = "Task", sync = true, key = "#root.methodName+ '_'+ #root.args[1] + #page + '_' + #size")1.4 具体情况在mybatisplus的日志中Row: 5, 1333, 333, [3037], [1], 1, 2025-11-05 16:10:45, null, 2025-11-05 16:10:45, 0也就是在mybatisplus读取数据的时候是正常的,但是List<Task> taskList = iPage.getRecords(); for (Task task1 : taskList) { System.out.println(task1); System.out.println(task1.getItemId() + "---" + task1.getItemNum()); }在输出taskList的时候Task(id=9, name=555, content=555, itemId=null, itemNum=null, onlineCount=1, createTime=Wed Nov 05 16:54:30 CST 2025, endTime=Thu Nov 06 00:00:00 CST 2025, updateTime=Wed Nov 05 16:54:30 CST 2025, deleted=0)null---null可以看到itemId itemNum均为nullredisTemplate配置了FastJsonRedisSerializer就是在转为 List<Integer>的时候出了问题2.解决方案我的Fastjson22.1 maven导入Fastjson2 <!-- fastJson --> <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 --> <dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version>2.0.59</version> </dependency>2.2 附上我的RedisConfig.javaimport com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; 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.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; import java.util.HashMap; import java.util.Map; @Configuration //@EnableCaching开启对SpringCache的支持(提供基于方法级别的缓存) @EnableCaching public class RedisConfig { /** * 默认缓存到期时间 */ private static final Integer DEFAULT_EXPIRE_TIME = 3600; @Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory, ObjectMapper objectMapper) { //便于开发自己编写redis RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); //序列化配置 GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(); // FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class); // FastJson2JsonRedisSerializer<Object> serializer = new FastJson2JsonRedisSerializer<>(Object.class); //string序列化 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key 采用string的序列化 template.setKeySerializer(stringRedisSerializer); template.setValueSerializer(serializer); //hansh的key也采用string的序列化方式 template.setHashKeySerializer(stringRedisSerializer); //hansh的value也采用string的序列化方式 template.setHashValueSerializer(serializer); //设置默认 template.setDefaultSerializer(serializer); template.afterPropertiesSet(); return template; } /** * 配置SpringCache基于方法级别的缓存的过期时间、key-value的序列化方式 * * @param connectionFactory * @return */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { //设置特有的Redis配置 Map<String, RedisCacheConfiguration> speCacheConfigurations = new HashMap<>(); //定制化的Cache为300s\400s\500s speCacheConfigurations.put("cacheName1",redisCacheConfiguration(300)); speCacheConfigurations.put("cacheName2",redisCacheConfiguration(400)); speCacheConfigurations.put("cacheName3",redisCacheConfiguration(500)); //根据redis缓存配置和redis连接工厂生成redis缓存管理器 RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory) .cacheDefaults(redisCacheConfiguration(DEFAULT_EXPIRE_TIME)) // 默认缓存配置 .withInitialCacheConfigurations(speCacheConfigurations) // 定制化的缓存配置 .build(); return redisCacheManager; } /** * RedisCacheConfiguration redis缓存配置 * * @param ttl 缓存过期时间 * @return */ public RedisCacheConfiguration redisCacheConfiguration(Integer ttl) { //redis缓存配置 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() //缓存生存时间60秒 .entryTtl(Duration.ofSeconds(ttl)) // 配置Key序列化(解决乱码的问题) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 配置Value序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair .fromSerializer( new GenericJackson2JsonRedisSerializer() // new FastJsonRedisSerializer<Object>(Object.class) )) // 不缓存空值 .disableCachingNullValues(); return config; } }2.3 创建JsonListIntegerTypeHandler.javaimport com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.TypeReference; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class JsonListIntegerTypeHandler extends BaseTypeHandler<List<Integer>> { // 插入/更新时:将List<Integer>转为JSON字符串存入数据库 @Override public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException { String jsonStr = JSON.toJSONString(parameter); // 例如:[3037, 3038] ps.setString(i, jsonStr); } // 查询时:从数据库读取字符串并解析为List<Integer> @Override public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException { String jsonStr = rs.getString(columnName); return parseJsonToList(jsonStr); } @Override public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String jsonStr = rs.getString(columnIndex); return parseJsonToList(jsonStr); } @Override public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String jsonStr = cs.getString(columnIndex); return parseJsonToList(jsonStr); } // 解析JSON字符串为List<Integer> private List<Integer> parseJsonToList(String jsonStr) { if (jsonStr == null || jsonStr.trim().isEmpty()) { return null; } // 使用FastJSON解析为List<Integer> return JSON.parseObject(jsonStr, new TypeReference<List<Integer>>() {}); } }2.4 在实体类上注解@TableField @Schema( description = "赠送礼物id") @TableField(value = "item_id", typeHandler = JsonListIntegerTypeHandler.class) private List<Integer> itemId; @Schema( description = "赠送礼物数量") @TableField(value = "item_Num", typeHandler = JsonListIntegerTypeHandler.class) private List<Integer> itemNum;2.5 最重要的在properties或者yaml中启动Handler下面的xxx换成你自己包的目录2.5.1 yamlmybatis-plus: typehandlers-package: com.xxx.handler2.5.2 propertiesmybaits-plus.typehandlers-package=com.xxx.handler3 结果展示Task(id=9, name=555, content=555, itemId=[3037], itemNum=[1], onlineCount=1, createTime=Wed Nov 05 16:54:30 CST 2025, endTime=Thu Nov 06 00:00:00 CST 2025, updateTime=Wed Nov 05 16:54:30 CST 2025, deleted=0)[3037]---[1]
2025年11月05日
1 阅读
0 评论
0 点赞
2021-12-03
Springboot跨域问题
原因之前Config类是implements WebMvcConfigurer//请求跨域 final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" }; @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 所有的当前站点的请求地址,都支持跨域访问。 .allowedOrigins("*") // 所有的外部域都可跨域访问。 如果是localhost则很难配置,因为在跨域请求的时候,外部域的解析可能是localhost、127.0.0.1、主机名 .allowCredentials(true) // 是否支持跨域用户凭证 .allowedHeaders("*") // 允许任何请求头 .allowedMethods(ORIGINS) // 当前站点支持的跨域请求类型是什么 .maxAge(3600); // 超时时长设置为1小时。 时间单位是秒。 } 除了图片上传接口之外都是正常的,但是上传图片报跨域异常。报错的问题是Redirect is not allowed for a preflight request原因是可能配置的跨域设置后启动。解决方案:import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { /** * cors support * @return */ @Bean public FilterRegistrationBean corsFilter() { // 注册CORS过滤器 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 是否支持安全证书 config.addAllowedOrigin("*"); // 允许任何域名使用 config.addAllowedHeader("*"); // 允许任何头 config.addAllowedMethod("*"); // 允许任何方法(post、get等) // 预检请求的有效期,单位为秒。 // config.setMaxAge(3600L); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0);//执行顺序的优先级 return bean; } }
2021年12月03日
47 阅读
0 评论
0 点赞
2020-12-04
宝塔部署War包的SpringBoot
1.调整pom.xml加入war<groupId>com.jam</groupId> <artifactId>childrenmonitor</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> //说明打包成war包 <name>childrenmonitor</name> <description>children Monitor and Control</description>声明tomcat内置服务,不做为外部服务。<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>2.添加Webapps目录双击下面 【4】 点击OK添加web.xml 这里一定要注意:web.xml的目录需要更改成之前在scr\main下面创建的webapp目录3.重写Application.java继承SpringBootServletInitializer添加下面代码:@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ChildrenmonitorApplication.class); }3.1完整Applicaiton.javaimport org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication @MapperScan("com.jam.dao") public class ChildrenmonitorApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ChildrenmonitorApplication.class); } public static void main(String[] args) { SpringApplication.run(ChildrenmonitorApplication.class, args); } }4.部署把war包放入服务器tomcat的webapps目录,自动解压。添加网站,目录选择webapps自动解压的目录在网站设置中开启tomcat
2020年12月04日
403 阅读
0 评论
0 点赞