springboot集成Junit、Mybatis、WebMVC、redis、dubbo框架

SpringBoot整合Junit

主要使用springboot整合junit单元测试,当前springboot默认集成的Junit5,介绍Junit5的新特性,之后使用springboot完成junit5的整合。

junit5 介绍

  • Spring Boot 2.2.0 版本开始引入 JUnit 5 作为单元测试默认库
  • 作为最新版本的JUnit框架,JUnit5与之前版本的Junit框架有很大的不同。由三个不同子项目的几个不同模块组成。
  • JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
  • JUnit Platform: Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
  • JUnit Jupiter: JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部 包含了一个测试引擎,用于在Junit Platform上运行。
  • JUnit Vintage: 由于JUint已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x,Junit3.x的测试引擎。

在这里插入图片描述

步骤:

1、构建工程添加依赖

<!--junit5版本,不兼容Junit4 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

<!--如果要继续兼容 junit4,自行引入Vintage-->
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2、创建测试类

  • 在测试类上加上注解 @SpringBootTest
  • 注入测试对象
@SpringBootTest
class TestThymeleafApplicationTests {
    @Autowired
    private ApplicationContext applicationContext;
    @Test
    void contextLoads() {
        System.out.println(applicationContext);
    }
}

SpringBoot整合Mybatis框架

1、创建maven工程添加依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<!--mysql驱动包-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<!--web模块-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2、在数据库中建表

mybatis数据库下的person表

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `gender` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `birthday` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

3、创建实体类

生成get、set方法,有参无参构造,toString方法

public class Person {
    private Integer id;
    private String name;
    private String gender;
    private Integer age;
    private String birthday;
}

4、创建接口和mapper.xml配置文件

  • 在mapper接口上加上@Mapper注解———–表示在spring容器中根据该接口生成代理类的对象

  • 或者在主启动类上加注解:@MapperScan(basePackages = “com.chenshuang.mapper”)

@Mapper
public interface PersonMapper {
    Person getPersonById(int id);
}
@SpringBootApplication
// 把com.chenshuang.mapper 根据整个包下的所有接口 都生成代理类的对象 交给spring容器管理
@MapperScan(basePackages = "com.chenshuang.mapper")
public class SpringbootMybitsApplication {

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

}

mapper.xml配置文件在resources/目录下创建————resources/mybatis/mapper/PersonMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chenshuang.mapper.PersonMapper">
    
    <select id="getPersonById" parameterType="int" resultType="Person">
        select * from person where id=#{id}
    </select>

</mapper>

5、配置application.yml(数据源,Myatis配置)

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///mybatis
    username: root
    password: 123456
#    默认的数据源
    type: com.zaxxer.hikari.HikariDataSource

mybatis:
#  #sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml
#   #配置了实体的别名
  type-aliases-package: com.chenshuang.entity
#  开启驼峰命名规则 不写全局局配置文件的配置都放在configuration对象当中
  configuration:
    map-underscore-to-camel-case: true

6、创建service层,在测试类中调用方法测试

@SpringBootApplication
// 把com.chenshuang.mapper 根据整个包下的所有接口 都生成代理类的对象 交给spring容器管理
@MapperScan(basePackages = "com.chenshuang.mapper")
public class SpringbootMybitsApplication {

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

}

SpringBoot整合webmvc框架

1、在pom文件中导入web依赖

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

2、创建控制器controller

@Controller
public class PersonController {

    @Resource
    private PersonService personService;

    @RequestMapping("person")
    @ResponseBody
    public Person getPerson(){
        Person person = personService.findPersonById(1);
        return person;
    }
}

3、启动服务器测试

访问地址:http://localhost:8080/person

在这里插入图片描述

SpringBoot整合redis框架

官网:https://spring.io/projects/spring-data-redis

RedisTemplate

API返回值类型说明
redisTemplate.opsForValue()ValueOperations操作 String 类型数据
redisTemplate.opsForHash()HashOperations操作 Hash 类型数据
redisTemplate.opsForList()ListOperations操作 List 类型数据
redisTemplate.opsForSet()SetOperations操作 Set 类型数据
redisTemplate.opsForZSet()ZSetOperations操作 SortedSet 类型数据
redisTemplate通用的命令

1、导入redis相关依赖

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

2、在 application.yml 配置 Redis 的信息

spring:
  redis:
    host: 192.168.146.132  # linux中的IP地址
    port: 6379
    password: 123456
    database: 0 # 几号库 (默认0号库)
    
    lettuce:
      pool:
        max-active: 8 # 最大连接
        max-idle: 8 # 最大空闲连接
        min-idle: 0 # 最小空闲连接
        max-wait: 100ms # 连接等待时间

3、测试类前注入redisTemplate,直接注入就好

@Resource
private RedisTemplate<String,String> redisTemplate;
  • 1 值类型操作:opsForValue()
 @Test
//    redisTemplate.opsForValue()
    void valuesTest() {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        // 存
        ops.set("username","张三李四");
        // 取
        String username = ops.get("username");
        System.out.println(username);
        // 删除
        redisTemplate.delete("username");
    }
  • 2 Set类型操作
@Test
//    redisTemplate.opsForSet()
    void setTest() {
        SetOperations<String, String> ops = redisTemplate.opsForSet();
        // 存
        ops.add("set","001","002","003");
        // 取
        Set<String> set = ops.members("set");
        System.out.println(set);
        // 删除单个元素
        ops.remove("set","003");
        // 删除key
//        redisTemplate.delete("set");
    }
  • 3 List集合操作:opsForList()
 @Test
//  右压栈  左压栈    ---
    void listTest() {
        ListOperations<String, String> ops = redisTemplate.opsForList();
        redisTemplate.delete("MyList");
        // 存--右压栈  ----从右边压入
        ops.rightPush("MyList","aaa");
        ops.rightPush("MyList","bbb");
        ops.rightPush("MyList","ccc");
        ops.rightPush("MyList","bbb");
        // 取 end为-1--表示取出全部元素
        List<String> myList = ops.range("MyList", 0, -1);
        System.out.println(myList);

        // 存--左压栈  ----从左边压入
        ops.leftPush("MyList","111");
        ops.leftPush("MyList","222");
        ops.leftPush("MyList","333");
        // 取 end为-1--表示取出全部元素
        List<String> myList1 = ops.range("MyList", 0, -1);
        System.out.println(myList1);


        // 根据索引查询元素
        String index = ops.index("MyList", 3);
        System.out.println(index);

        // 移出某个元素的值
        ops.remove("MyList",2,"bbb");
        List<String> range = ops.range("MyList", 0, -1);
        System.out.println(range);

    }
  • 4 Hash类型操作:opsForHash()
@Test
//    redisTemplate.opsForHash()
    void hashMapTest() {
        HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
        // 存入值
        ops.put("user","username","mrzhang");
        ops.put("user","address","beijing");
        ops.put("user","age","18");
        // 提取所有的KEY
        Set<Object> user = ops.keys("user");
        System.out.println(user); // username address age

        // 提取所有的值
        List<Object> list = ops.values("user");
        System.out.println(list); // [mrzhang, beijing, 18]

        // 根据KEY提取值
        String o = (String) ops.get("user", "username");
        System.out.println(o);

        // 根据KEY移除值
        ops.delete("user", "username");
    }

SpringBoot整合dubbo框架

模拟分布式项目,编写提供者模块:springboot_dubbo_providers

1、导入zkClient、springboot整合dubbo依赖

<!-- dubbo的依赖 -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.6</version>
</dependency>
<!-- zk的依赖 -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-dependencies-zookeeper</artifactId>
    <version>2.7.6</version>
    <type>pom</type>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2、配置application.yml

server:
  port: 8081
dubbo:
  registry:
    address: zookeeper://192.168.146.132:2181
    timeout: 60000
  protocol:
    name: dubbo
    port: 20881
  application:
    name: springboot_providers
  scan:
    base-packages: com.chenshuang.service.impl

3、在虚拟机中开启zookeeper

4、编写接口,写实现类,以及实体类

注意实现类中引用注解【org.apache.dubbo.config.annotation.Service】

// 引用注解:--org.apache.dubbo.config.annotation.Service
@Service
public class PersonServiceImpl implements PersonService {

}

在这里插入图片描述

模拟分布式项目,编写消费者模块:springboot_dubbo_customers

1、pom文件中导入zkClient、springboot整合dubbo依赖

2、配置application.yml

server:
  port: 8081
dubbo:
  registry:
    address: zookeeper://192.168.146.132:2181
    timeout: 60000
  protocol:
    name: dubbo
    port: 20881
  application:
    name: springboot_providers
  scan:
    base-packages: com.chenshuang.service.impl

3、编写contoller层

注意调用接口应和提供者调用的接口一样。用注解@Reference声明

@Reference:import org.apache.dubbo.config.annotation.Reference;

@Controller
public class PersonController {

    @Reference
    private PersonService personService;

    @RequestMapping("/getPersonById")
    @ResponseBody
    public Person getPersonById(int id){
        Person person = personService.getPersonById(1);
        return person;
    }

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-frGzYsqv-1657028331285)(E:\Java资料\笔记整理\JavaUp\笔记整理\springboot_集成.assets\image-20220619235844494.png)]

4、在浏览器中访问方法查看效果

http://localhost:8082/getPersonById?id=1

:import org.apache.dubbo.config.annotation.Reference;**

@Controller
public class PersonController {

    @Reference
    private PersonService personService;

    @RequestMapping("/getPersonById")
    @ResponseBody
    public Person getPersonById(int id){
        Person person = personService.getPersonById(1);
        return person;
    }

}

4、在浏览器中访问方法查看效果

http://localhost:8082/getPersonById?id=1

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮卡丘不断更

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值