springboot常用组件的集成
创始人
2024-01-21 07:31:09
0

目录

springboot常用组件的集成

1.创建项目

2. web服务器配置

3. 配置数据库

4. 配置mybatis

5. 开启事务

6.aop配置

7. pagehelper分页

3. druid数据库连接池

4. 集成redis

编写一个controller用于测试

2.手动装配redis


1.创建项目

1.idea创建项目

创建步骤 :File --> New --> project,,,-->Spring initializr-->选择项目所需要的架包

项目创建完成后可以查看pom.xml文件,上面选择的的第三方组件已经加入到pom.xml中了。

pom.xml:

org.mybatis.spring.bootmybatis-spring-boot-starter2.1.1

mysqlmysql-connector-java8.0.30

2. web服务器配置

打开application.properties文件

#端口号
server.port=8080
#指定上下文路径
server.servlet.context-path=/
#指定url编码
server.tomcat.uri-encoding=utf-8

3. 配置数据库

打开application.properties文件

#驱动
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
#数据库连接
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/db_text?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
#用户名
spring.datasource.username = root
#密码
spring.datasource.password = 123456

mybatas-plus配置

 

4. 配置mybatis

打开application.properties文件

#mybatis核心配置文件
mybatis.config-locations=classpath:mybatis-config.xml
​
#mybatis xml配置文件的位置
mybatis.mapper-locations=classpath:/mapper/**/*.xml
​
#在控制台输出执行的sql语句
mybatis.configuration.logimpl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-config.xml文件内容:




















5. 开启事务

在启动类上加入如下注解:

 

在需要进行事务管理的类或方法上加入事务注解就可以了(@Transactional)

6.aop配置

org.springframework.bootspring-boot-starter-aop

7. pagehelper分页

  1. pom.xml

com.github.pagehelperpagehelper-spring-boot-starter 1.2.12

2)application.properties

# -------------------- pagehelper B ---------------------------
pagehelper.helper-dialect= mysql
#pagehelper.reasonable=true
#pagehelper.support-methods-arguments=true
#pagehelper.params=count=countSql
# -------------------- pagehelper E ---------------------------
  1. 将课件提供的PageBean.java, PagingInterceptor.java,

1.定义注解

package com.example.springboot1.annotation;
​
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
​
/*** @author L* @site www.xiaomage.com* @company xxx公司* @create  2022-06-10 9:10*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Paging {
}

2.定义切面

package com.example.springboot1.aop;
​
import com.example.springboot1.utils.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
​
import java.util.List;
​
/*** @author L* @site www.xiaomage.com* @company xxx公司* @create  2022-06-09 16:15*/
​
@Component
@Aspect
@Order(1)
public class PagingAOP {
​
​//@Around("execution(* com.zking.mybatisdemo..*.*Page(..))")@Around("@annotation(com.example.springboot1.annotation.Paging)")public Object around(ProceedingJoinPoint point) throws Throwable {
​Object[] args = point.getArgs();
​PageBean pageBean = null;for(Object arg: args) {if(arg instanceof PageBean) {pageBean = (PageBean)arg;if(pageBean != null && pageBean.isPagination()) {PageHelper.startPage(pageBean.getPage(), pageBean.getRows());}}}
​Object rv = point.proceed();
​if(pageBean != null && pageBean.isPagination()) {PageInfo info = new PageInfo((List)rv);pageBean.setTotal(Long.valueOf(info.getTotal()).intValue());}
​return rv;}
​
}
​

3.定义分页工具类

package com.example.springboot1.utils;
​
import com.mysql.cj.util.StringUtils;
​
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
​
public class PageBean {
​/*** 页码*/private int page = 1;
​/*** 每页显示的记录数*/private int rows = 10;
​/*** 总记录数*/private int total = 0;
​/*** 是否分页*/private boolean pagination = true;
​/*** 记录查询的url,以便于点击分页时再次使用*/private String url;
​/*** 存放请求参数,用于生成隐藏域中的元素*/private Map parameterMap;
​/*** 根据传入的Request初始化分页对象* @param request*/public void setRequest(HttpServletRequest request) {
​if(!StringUtils.isNullOrEmpty(request.getParameter("page"))) {this.page = Integer.valueOf(request.getParameter("page"));}if(!StringUtils.isNullOrEmpty(request.getParameter("rows"))) {this.rows = Integer.valueOf(request.getParameter("rows"));}if(!StringUtils.isNullOrEmpty(request.getParameter("pagination"))) {this.pagination = Boolean.valueOf(request.getParameter("pagination"));}
​this.url = request.getRequestURI();this.parameterMap = request.getParameterMap();
​request.setAttribute("pageBean", this);}
​
​public int getPage() {return page;}
​
​public void setPage(int page) {this.page = page;}
​
​public int getRows() {return rows;}
​
​public void setRows(int rows) {this.rows = rows;}
​
​public int getTotal() {return total;}
​
​public void setTotal(int total) {this.total = total;}
​public boolean isPagination() {return pagination;}
​public void setPagination(boolean pagination) {this.pagination = pagination;}
​public String getUrl() {return url;}
​public void setUrl(String url) {this.url = url;}
​public Map getParameterMap() {return parameterMap;}
​public void setParameterMap(Map parameterMap) {this.parameterMap = parameterMap;}
​//计算起始页码public int getStartIndex() {return (this.page - 1) * this.rows;}
​//获取总页数public int getTotalPage() {if (this.getTotal() % this.rows == 0) {return this.getTotal() / this.rows;} else {return this.getTotal() / this.rows + 1;}}
​//上一页public int getPreviousPage() {return this.page - 1 > 0 ? this.page - 1 : 1;}
​//下一页public int getNextPage() {return this.page + 1 > getTotalPage() ? getTotalPage() : this.page + 1;}
​
}

4)集成结束,可以编写测试方法进行测试

 

然后调用方法测试即可

注意此处 ,如使用两次界面 paging需要在最上方 否则失效

3. druid数据库连接池

阿里开源的数据库连接池,使用java开发,提供强大的监控和扩展功能,可以替换DBCP和C3P0连接池,性能要比其他的连接池要好。 1)pom.xml

com.alibabadruid-spring-boot-starter1.1.21
  1. application.properties

#--------------------- druid config B ------------------------
#config druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化时建立物理连接的个数
spring.datasource.druid.initial-size=5
#最小连接池数量
spring.datasource.druid.min-idle=5
#最大连接池数量 maxIdle已经不再使用
spring.datasource.druid.max-active=20
#获取连接时最大等待时间,单位毫秒
spring.datasource.druid.max-wait=60000
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
spring.datasource.druid.test-while-idle=true
#既作为检测的间隔时间又作为testWhileIdel执行的依据
spring.datasource.druid.time-between-eviction-runs-millis=60000
#销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
spring.datasource.druid.min-evictable-idle-time-millis=30000
#用来检测连接是否有效的sql 必须是一个查询语句
#mysql中为 select 1
#oracle中为 select 1 from dual
spring.datasource.druid.validation-query=select 1
#申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-borrow=false
#归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-return=false
#当数据库抛出不可恢复的异常时,抛弃该连接
#spring.datasource.druid.exception-sorter=true
#是否缓存preparedStatement,mysql5.5+建议开启
spring.datasource.druid.pool-prepared-statements=true
#当值大于0时poolPreparedStatements会自动修改为true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#配置扩展插件
spring.datasource.druid.filters=stat,wall
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true
​
# WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
#是否启用StatFilter默认值true
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
#经常需要排除一些不必要的url,比如*.js,/jslib/*等等
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
​
#Druid内置提供了一个StatViewServlet用于展示Druid的统计信息
#设置访问druid监控页的账号和密码,默认没有
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
​
#DruidStatView的servlet-mapping
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
#允许列表,只有配置在此处的ip才允许访问durid监控平台
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
#拒绝列表,配置下此处的ip将被拒绝访问druid监控平台
spring.datasource.druid.stat-view-servlet.deny=
#--------------------- druid config E ------------------------

application.yml配置

spring:datasource:url: jdbc:mysql://ip:port/数据库?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=falseusername: rootpassword: driver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourcedruid:#初始化大小initialSize: 5#最小值minIdle: 5#最大值maxActive: 20#最大等待时间,配置获取连接等待超时,时间单位都是毫秒msmaxWait: 60000#配置间隔多久才进行一次检测,检测需要关闭的空闲连接timeBetweenEvictionRunsMillis: 60000#配置一个连接在池中最小生存的时间minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,#'wall'用于防火墙,SpringBoot中没有log4j,我改成了log4j2filters: stat,wall,log4j2#最大PSCache连接maxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: true# 通过connectProperties属性来打开mergeSql功能;慢SQL记录connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500# 配置StatFilterweb-stat-filter:#默认为false,设置为true启动enabled: trueurl-pattern: "/*"exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"#配置StatViewServletstat-view-servlet:url-pattern: "/druid/*"#允许那些ipallow: 127.0.0.1login-username: adminlogin-password: 123456#禁止那些ipdeny: 192.168.1.102#是否可以重置reset-enable: true#启用enabled: true

4. 集成redis

  1. pom.xml

org.springframework.bootspring-boot-starter-data-redis
  1. application.properties

# -------------------- redis config B -------------------------
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.24
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=100
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.jedis.timeout=1000
# -------------------- redis config E -------------------------

yml文件配置

 redis:database: 1host: 120.79.61.66   # Redis服务器地址port: 6379           # Redis服务器连接端口password: 123456     # Redis服务器连接密码(默认为空)jedis:pool:max-active: 200     # 连接池最大连接数(使用负值表示没有限制)max-wait: -1        # 连接池最大阻塞等待时间(使用负值表示没有限制)max-idle: 10        # 连接池中的最大空闲连接min-idle: 2         # 连接池中的最小空闲连接connect-timeout: 6000   # 连接超时时间(毫秒)

  1. 编写一个controller用于测试

/*** 用于测试redis集成* @author Administrator* @create 2019-12-1822:16*/
@RestController
public class RedisTestController {
​@Resourceprivate RedisTemplate redisTemplate;
​@RequestMapping(value = "/redis")public Object redis() {
​String name = "redis test";redisTemplate.opsForValue().set("redisTest", name);
​Map map = new HashMap<>();map.put("code", 1);map.put("msg", "操作成功");
​return map;}
​
}

可以通过postman进行测试,如果正常在redis中添加key,则说明集成成功。

配置文件中需要写入redis基本配置

 redis:database: 1host: 120.79.61.66   # Redis服务器地址port: 6379           # Redis服务器连接端口password: 123456     # Redis服务器连接密码(默认为空)jedis:pool:max-active: 200     # 连接池最大连接数(使用负值表示没有限制)max-wait: -1        # 连接池最大阻塞等待时间(使用负值表示没有限制)max-idle: 10        # 连接池中的最大空闲连接min-idle: 2         # 连接池中的最小空闲连接connect-timeout: 6000   # 连接超时时间(毫秒)

手动配置后 利用json进行转换 所需架包

  com.fasterxml.jackson.corejackson-databind2.13.3

2.手动装配redis

package com.example.springboot1.confing;
​
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
​
import java.time.Duration;
​
/*** 配置rdeis 中的数据是 json 加入保存*/
​
@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
@Slf4j
public class RedisCacheConfig {private Duration timeToLive = Duration.ZERO;public void setTimeToLive(Duration timeToLive) {this.timeToLive = timeToLive;}
​
​
​@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {// 创建redisTemplateRedisTemplate redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);
​// 使用Jackson2JsonRedisSerialize替换默认序列化Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
​ObjectMapper objectMapper = new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
​jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
​// key采用String的序列化方式redisTemplate.setKeySerializer(new StringRedisSerializer());// value序列化方式采用jacksonredisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// hash的key也采用String的序列化方式redisTemplate.setHashKeySerializer(new StringRedisSerializer());// hash的value序列化方式采用jacksonredisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}
​
​@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory) {RedisSerializer redisSerializer = new StringRedisSerializer();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);
​// 配置序列化(解决乱码的问题)RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(timeToLive).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();
​RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();return cacheManager;}
​
​
​
}

上一篇:攻防世界Running

下一篇:UNet - unet网络

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
一帆风顺二龙腾飞三阳开泰祝福语... 本篇文章极速百科给大家谈谈一帆风顺二龙腾飞三阳开泰祝福语,以及一帆风顺二龙腾飞三阳开泰祝福语结婚对应...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
美团联名卡审核成功待激活(美团... 今天百科达人给各位分享美团联名卡审核成功待激活的知识,其中也会对美团联名卡审核未通过进行解释,如果能...