该实例目的是为了让同学们快速学会使用SpringBoot集成搭建SpringMVC、Spring、MyBatis及Redis
创建新的数据库springboot,指定数据库字符编码为utf-8
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for t_student -- ---------------------------- DROP TABLE IF EXISTS `t_student`; CREATE TABLE `t_student` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `age` int NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of t_student -- ---------------------------- INSERT INTO `t_student` VALUES (1, 'zhangsan', 25); INSERT INTO `t_student` VALUES (2, 'lisi', 28); INSERT INTO `t_student` VALUES (3, 'wangwu', 23); INSERT INTO `t_student` VALUES (4, 'Tom', 21); INSERT INTO `t_student` VALUES (5, 'Jck', 55); INSERT INTO `t_student` VALUES (6, 'Lucy', 27); INSERT INTO `t_student` VALUES (7, 'zhaoliu', 75); SET FOREIGN_KEY_CHECKS = 1;
按照Dubbo官方开发建议,创建一个接口项目,该项目只定义接口和model类
项目名称:009-springboot-ssm-dubbo-exterface

- /*
- * ClassName:StudentService
- * Package:com.abc.springboot.com.suke.springboot.service
- * Description:<br/>
- * */
- public interface StudentService {
-
- /*
- * 获取学生总人数
- *
- * @return
- * */
- Long queryAllStudentCount();
- }
- public class Student implements Serializable {
- private Integer id;
-
- private String name;
-
- private Integer age;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
- }
项目名称:010-springboot-ssm-dubbo-provider

- <!--SpringBoot集成Dubbo起步依赖-->
- <dependency>
- <groupId>com.alibaba.spring.boot</groupId>
- <artifactId>dubbo-spring-boot-starter</artifactId>
- <version>2.0.0</version>
- </dependency>
-
- <!--zookeeper注册中心-->
- <dependency>
- <groupId>com.101tec</groupId>
- <artifactId>zkclient</artifactId>
- <version>0.10</version>
- <exclusions>
- <exclusion>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <!--MyBatis集成SpringBoot框架起步依赖-->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.0.0</version>
- </dependency>
-
- <!--连接MySQL数据库驱动-->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
-
- <!--SpringBoot集成Redis起步依赖-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
-
- <!--dubbo接口工程-->
- <dependency>
- <groupId>com.suke.springboot</groupId>
- <artifactId>009-springboot-ssm-dubbo-exterface</artifactId>
- <version>1.0-SNAPSHOT</version>
- </dependency>
在pom文件中的build标签中添加
- <!--手动指定资源配置文件路径-->
- <!--目的:将数据持久层映射文件编译到classpath中-->
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*.xml</include>
- </includes>
- </resource>
- </resources>
(1)添加插件
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!--mybatis代码自动生成插件--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <!--配置文件的位置--> <configurationFile>GeneratorMapper.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins>(2)将配置文件存放到项目根据目录
(3)GeneratorMapper.xml内容如下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 --> <classPathEntry location="D:\IT\Java\maven_repository\mysql\mysql-connector-java\8.0.19\mysql-connector-java-8.0.19.jar"/> <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 --> <context id="tables" targetRuntime="MyBatis3"> <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 --> <commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- 配置数据库连接信息 --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8& useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true" userId="root" password="root"> </jdbcConnection> <!-- 生成 com.suke.springboot.model 类,targetPackage 指定 com.suke.springboot.model 类的包名, targetProject 指定 生成的 com.suke.springboot.model 放在 eclipse 的哪个工程下面--> <javaModelGenerator targetPackage="com.suke.springboot.com.suke.springboot.model" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> <property name="trimStrings" value="false"/> </javaModelGenerator> <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的 包名, targetProject 指定生成的 mapper.xml 放在 eclipse 的哪个工程下面 --> <sqlMapGenerator targetPackage="com.suke.springboot.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包 名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.suke.springboot.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 数据库表名及对应的 Java 模型类名 --> <!-- 指定数据库表 schema:表示数据库名称--> <table tableName="tb_student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> </context> </generatorConfiguration>(4)点击插件生成

- #配置内嵌Tomcat端口号
- server.port=9010
- #配置项目上下文根
- server.servlet.context-path=/010-springboot-ssm-dubbo-provider
- #数据库的配置
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
- spring.datasource.username=root
- spring.datasource.password=root
- #配置dubbo服务提供者
- spring.application.name=010-springboot-ssm-dubbo-provider
- #表示是服务提供者
- spring.dubbo.server=true
- #注册中心地址
- spring.dubbo.registry=zookeeper://192.168.60.130:2181
- #配置redis连接信息
- spring.redis.host=192.168.60.130
- spring.redis.port=6379
- spring.redis.password=123456
- /*
- * ClassName:StudentServiceImpl
- * Package:com.suke.springboot.service
- * Description:<br/>
- * */
- @Service(interfaceClass = StudentService.class, timeout = 20000, retries = 3, version = "1.0.0")
- @Component //将接口实现类交给spring容器进行管理
- public class StudentServiceImpl implements StudentService {
-
- @Autowired
- private StudentMapper studentMapper;
-
- @Autowired
- private RedisTemplate redisTemplate;
-
- @Override
- public Long queryAllStudentCount() {
- //设置key键,序列化,与功能无关
- redisTemplate.setKeySerializer(new StringRedisSerializer());
- //从redis缓存中获取总人数
- Long allStudentCount = (Long) redisTemplate.opsForValue().get("allStudentCount");
- //判断学生总人数是否为空
- if (allStudentCount == null) {
- //设置同步代码块
- synchronized (this) {
- //再次从redis缓存中获取学生总人数
- allStudentCount = (Long) redisTemplate.opsForValue().get("allStudentCount");
- //双重检测判断缓存中是否有数据
- if (allStudentCount == null) {
- System.out.println("----查询数据库-----");
- //从数据库查询
- allStudentCount = studentMapper.selectAllStudentCount();
- //将值再存放到redis缓存中
- redisTemplate.opsForValue().set("allStudentCount", allStudentCount, 20, TimeUnit.SECONDS);
- } else {
- System.out.println("-----缓存命中-------");
- }
- }
- } else {
- System.out.println("-----缓存命中-------");
- }
- return allStudentCount;
- }
- }
- //@Mapper
- @Repository
- public interface StudentMapper {
-
- /*
- * 获取学生总人数
- * */
- Long selectAllStudentCount();
- }
- <?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.suke.springboot.mapper.StudentMapper">
- <resultMap id="BaseResultMap" type="com.suke.springboot.model.Student">
- <id column="id" jdbcType="INTEGER" property="id"/>
- <result column="name" jdbcType="VARCHAR" property="name"/>
- <result column="age" jdbcType="INTEGER" property="age"/>
- </resultMap>
- <sql id="Base_Column_List">
- id
- , name, age
- </sql>
- <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
- select
- <include refid="Base_Column_List"/>
- from tb_student
- where id = #{id,jdbcType=INTEGER}
- </select>
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
- delete
- from tb_student
- where id = #{id,jdbcType=INTEGER}
- </delete>
- <insert id="insert" parameterType="com.suke.springboot.model.Student">
- insert into tb_student (id, name, age)
- values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
- </insert>
- <insert id="insertSelective" parameterType="com.suke.springboot.model.Student">
- insert into tb_student
- <trim prefix="(" suffix=")" suffixOverrides=",">
- <if test="id != null">
- id,
- </if>
- <if test="name != null">
- name,
- </if>
- <if test="age != null">
- age,
- </if>
- </trim>
- <trim prefix="values (" suffix=")" suffixOverrides=",">
- <if test="id != null">
- #{id,jdbcType=INTEGER},
- </if>
- <if test="name != null">
- #{name,jdbcType=VARCHAR},
- </if>
- <if test="age != null">
- #{age,jdbcType=INTEGER},
- </if>
- </trim>
- </insert>
- <update id="updateByPrimaryKeySelective" parameterType="com.suke.springboot.model.Student">
- update tb_student
- <set>
- <if test="name != null">
- name = #{name,jdbcType=VARCHAR},
- </if>
- <if test="age != null">
- age = #{age,jdbcType=INTEGER},
- </if>
- </set>
- where id = #{id,jdbcType=INTEGER}
- </update>
- <update id="updateByPrimaryKey" parameterType="com.suke.springboot.model.Student">
- update tb_student
- set name = #{name,jdbcType=VARCHAR},
- age = #{age,jdbcType=INTEGER}
- where id = #{id,jdbcType=INTEGER}
- </update>
-
- <select id="selectAllStudentCount" resultType="long">
- select count(*)
- from tb_student
- </select>
- </mapper>
- @SpringBootApplication
- @EnableDubboConfiguration//开启Dubbo配置支持
- @MapperScan("com.suke.springboot.mapper")//扫描数据持久层
- public class Application {
-
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
-
- }
项目名称:011-springboot-ssm-dubbo-consumer

- <!--SpringBoot集成Dubbo起步依赖-->
- <dependency>
- <groupId>com.alibaba.spring.boot</groupId>
- <artifactId>dubbo-spring-boot-starter</artifactId>
- <version>2.0.0</version>
- </dependency>
-
- <!--zookeeper注册中心-->
- <dependency>
- <groupId>com.101tec</groupId>
- <artifactId>zkclient</artifactId>
- <version>0.10</version>
- <exclusions>
- <exclusion>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <!--dubbo接口工程-->
- <dependency>
- <groupId>com.suke.springboot</groupId>
- <artifactId>009-springboot-ssm-dubbo-exterface</artifactId>
- <version>1.0-SNAPSHOT</version>
- </dependency>
- #配置内嵌Tomcat端口号
- server.port=9011
- #配置项目上下文根
- server.servlet.context-path=/011-springboot-ssm-dubbo-consumer
- #配置zookeeper注册中心
- spring.application.name=011-springboot-ssm-dubbo-consumer
- spring.dubbo.registry=zookeeper://192.168.60.130:2181
- /*
- * ClassName:StudentController
- * Package:com.suke.springboot.web
- * Description:<br/>
- * */
- @RestController
- public class StudentController {
-
- @Reference(interfaceClass = StudentService.class, version = "1.0.0", timeout = 20000, retries = 3, check = false)
- StudentService studentService;
-
- @GetMapping(value = "/springBoot/student/count")
- public Object studentCount(HttpServletRequest request) {
-
- //创建线程池
- ExecutorService executorService = Executors.newFixedThreadPool(16);
- //模拟千人并发
- for (int i = 0; i < 1000; i++) {
- executorService.submit(new Runnable() {
- @Override
- public void run() {
- studentService.queryAllStudentCount();
- }
- });
- }
- return "学生总人数:" + 7;
- }
- }
- @SpringBootApplication
- @EnableDubboConfiguration //开启dubbo支持配置
- public class Application {
-
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
-
- }
(1)启动redis服务
01-Centos7安装Redis和启动Redis
https://blog.csdn.net/qq_45037155/article/details/124679838
[root@Suke /]# cd /usr/local/redis-4.0.6/src/ [root@Suke src]# ./redis-server ../redis.conf &
(2)启动Zookeeper服务
Zookeeper启动
https://blog.csdn.net/qq_45037155/article/details/124959703
./zkServer.sh start
[root@Suke ~]# cd /usr/local/apache-zookeeper-3.5.5-bin/bin/ [root@Suke bin]# ./zkServer.sh help ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.5.5-bin/bin/../conf/zoo.cfg Usage: ./zkServer.sh [--config <conf-dir>] {start|start-foreground|stop|restart|status|print-cmd} [root@Suke bin]# ./zkServer.sh start ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.5.5-bin/bin/../conf/zoo.cfg Starting zookeeper ... STARTED
(4)启动011-springboot-ssm-dubbo-consumer



