SpringBoot常见组件集成

目录

一、mybatis集成

web服务器配置

配置数据库

配置mybatis

开启事务

​编辑

二、AOP配置

三. druid数据库连接池

四、集成Redis

一、mybatis集成

  • 创建项目完成之后,在pom.xml中导入需要的组件

    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.1.1

    org.mybatis
    mybatis-spring
    1.3.2

    mysql
    mysql-connector-java
    ${mysql.driver.version}
  • *web服务器配置

打开application.properties文件,填入如下代码

#端口号
server.port=8080
#指定上下文路径
server.servlet.context-path=/
#指定url编码
server.tomcat.uri-encoding=utf-8
  • *配置数据库
#驱动
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#数据库连接
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
#用户名
spring.datasource.username = root
#密码
spring.datasource.password = 123456
  • *配置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文件内容:


  • *开启事务

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

@EnableTransactionManagement表示开启事务支持

@MapperScan表示指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类

@SpringBootApplication表示用来标注一个主程序类,说明这是一个Spring Boot应用

SpringBoot常见组件集成

二、AOP配置

1、在pom.xml里面配置aop


   org.springframework.boot
   spring-boot-starter-aop

2、在pom.xml里面配置pagehelper分页


   com.github.pagehelper
   pagehelper-spring-boot-starter
   1.2.12
  • application.properties
-------------------- pagehelper B ---------------------------
pagehelper.helper-dialect= mysql
#pagehelper.reasonable=true
#pagehelper.support-methods-arguments=true
#pagehelper.params=count=countSql
-------------------- pagehelper E ---------------------------
  • 导入PageBean.java, PagingAOP.java这两个类以及Paging自定义注解

PageBean.java

package com.yian.springdemo.utils;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.mysql.jdbc.StringUtils;

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;
    }

}
PagingAOP.java
package com.yian.springdemo.aop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yian.springdemo.utils.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Aspect
public class PagingAOP {

    //@Around("execution(* com.zking.mybatisdemo..*.*Page(..))")
    @Around("@annotation(com.yian.springdemo.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;
    }

}

Paging

package com.yian.springdemo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Paging {
}
  • 集成结束后可以编写测试方法进行测试。测试的案例主要代码如下:SrudentServiceImpl

SrudentServiceImpl.java

package com.yian.springdemo.service;

import com.yian.springdemo.annotation.Paging;
import com.yian.springdemo.mapper.StudentMapper;
import com.yian.springdemo.model.Student;
import com.yian.springdemo.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SrudentServiceImpl implements ISrudentService {

    @Autowired
    private StudentMapper mapper;

    @Paging
    @Override
    public List listStu(Student student, PageBean pageBean) {
        return mapper.listStu(student);
    }
}

测试类

package com.yian.springdemo.service;

import com.yian.springdemo.model.Student;
import com.yian.springdemo.utils.PageBean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SrudentServiceImplTest {

    @Autowired
    private  ISrudentService service;

    @Test
    public void listStu() {
        Student student = new Student();
        PageBean pageBean = new PageBean();
        pageBean.setRows(1);
        List students = service.listStu(student,pageBean);
        students.forEach(t-> System.out.println(t));

        }

    }

测试结果如下:

SpringBoot常见组件集成

三. druid数据库连接池

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

1)pom.xml


    com.alibaba
    druid-spring-boot-starter
    1.1.21

2)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.properties里面均为admin)

SpringBoot常见组件集成

进入的页面如下

SpringBoot常见组件集成

四、集成Redis

1)pom.xml


   org.springframework.boot
   spring-boot-starter-data-redis

2)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 -------------------------

3)编写一个controller用于测试

/**
 * 用于测试redis集成
 * @author Administrator
 * @create 2019-12-1822:16
 */
@RestController
public class RedisTestController {

    @Resource
    private 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;
    }

}

写到此步运行成功,打开虚拟机查看可能会出现如下图所示 为什么会这样显示是因为写到这步只是使用了默认的配置(jdk序列化机制),没有配置key值应该用什么样的方式显示。

SpringBoot常见组件集成

这个时候我们需要一个配置类,使用自己的配置

@Configuration
@EnableCaching
public class CacheConfig {

    private static final Logger log = LoggerFactory.getLogger(CacheConfig.class);

    @Bean
    public JedisConnectionFactory redisConnectionFactory() throws IOException {

        ClassPathResource resource = new ClassPathResource("/redis.properties");
        InputStream in = resource.getInputStream();
        Properties prop = new Properties();
        prop.load(in);

        String host = prop.getProperty("redis.host");
        Integer port = Integer.valueOf(prop.getProperty("redis.port"));
        Integer maxIdle = Integer.valueOf(prop.getProperty("redis.maxIdle"));
        Integer maxTotal = Integer.valueOf(prop.getProperty("redis.maxTotal"));
        Integer maxWaitMillis = Integer.valueOf(prop.getProperty("redis.maxWaitMillis"));
        boolean testOnBorrow =  Boolean.valueOf(prop.getProperty("redis.testOnBorrow"));

        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);

        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
        redisConnectionFactory.setHostName(host);
        redisConnectionFactory.setPort(port);
        redisConnectionFactory.setPoolConfig(poolConfig);

        return redisConnectionFactory;
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(cf);

        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        return redisTemplate;
    }

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

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //这里可以设置一个默认的过期时间
        cacheManager.setDefaultExpiration(300);
        return cacheManager;
    }

    @Bean
    public KeyGenerator customKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

}

运行成功后效果如下:

SpringBoot常见组件集成

Original: https://blog.csdn.net/weixin_62270300/article/details/127823544
Author: 時宜
Title: SpringBoot常见组件集成

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/660878/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球