亲宝软件园·资讯

展开

SpringBoot集成SSM、Dubbo、Redis、JSP SpringBoot集成SSM、Dubbo、Redis、JSP的案例小结及思路讲解

张起灵-小哥 人气:0
想了解SpringBoot集成SSM、Dubbo、Redis、JSP的案例小结及思路讲解的相关内容吗,张起灵-小哥在本文为您仔细讲解SpringBoot集成SSM、Dubbo、Redis、JSP的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot集成SSM、Dubbo、Redis、JSP,SpringBoot,SSM、Dubbo、Redis、JSP,下面大家一起来学习吧。

1.思路讲解

这个案例其实就是SpringBoot集成SSM、Dubbo、Redis、JSP,看起来集成了一大堆,感觉挺麻烦的,但实际上并不是很麻烦,下面我来说一下我的思路:

接口工程:存放实体bean和业务接口

服务提供者:它是一个SpringBoot框架web项目,集成MyBatis、Redis

1)pom文件中添加依赖:MyBatis、MySQL驱动、Dubbo、zookeeper、redis、接口工程。

2)配置springboot核心配置文件(连接数据库、连接redis、dubbo、内嵌tomcat)

服务消费者:它也是一个SpringBoot框架web项目,集成JSP、Dubbo

2)配置springboot核心配置文件(dubbo、内嵌tomcat、视图解析器)

1)pom文件中添加依赖:Dubbo、zookeeper、接口工程、解析jsp页面的依赖。

文章比较长,因为代码比较多,大家一定要有这个耐心去看完,相信我讲的还是有点用的!!!

2.案例分析

这里SpringBoot集成MyBatis,我用的是MyBatis逆向工程来直接生成的实体bean、dao、mapper,所以这里首先给出MyBatis逆向工程的配置文件。

这个文件主要是负责生成你项目中的实体bean、dao、mapper,那么再加上集成dubbo的情况下,我们的实体bean是需要放在接口工程中的,而dao、mapper则需要放在服务提供者中,所以在MyBatis逆向工程的配置文件中,需要将实体bean的生成位置改为第一个接口工程的绝对路径。数据库这里的表结构和数据,我就不再给出了,大家自行创建一下就可以了。

<?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="E:\mysql-connector-java-5.1.9.jar"/>
        <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 -->
        <context id="tables" targetRuntime="MyBatis3">
            <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!-- 配置数据库连接信息 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/springboot"
                            userId="root"
                            password="12345678">
            </jdbcConnection>
            <!-- 生成 entity 类,targetPackage 指定 entity 类的包名, targetProject指定生成的 entity 放在 IDEA 的哪个工程下面-->
            <javaModelGenerator targetPackage="com.szh.springboot.entity"
                                targetProject="D:\BaiduNetdiskDownload\014-springboot-ssm-dubbo-interface\src\main\java">
                <property name="enableSubPackages" value="false"/>
                <property name="trimStrings" value="false"/>
            </javaModelGenerator>
            <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的包名, targetProject 指定生成的 mapper.xml 放在 IDEA 的哪个工程下面 -->
            <sqlMapGenerator targetPackage="com.szh.springboot.mapper"
                             targetProject="src/main/java">
                <property name="enableSubPackages" value="false"/>
            </sqlMapGenerator>
            <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包名, targetProject 指定生成的 Mapper 接口放在 IDEA 的哪个工程下面 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="com.szh.springboot.mapper"
                                 targetProject="src/main/java">
                <property name="enableSubPackages" value="false"/>
            </javaClientGenerator>
            <!-- 数据库表名及对应的 Java 模型类名 -->
            <table tableName="t_student" domainObjectName="Student"
                   enableCountByExample="false"
                   enableUpdateByExample="false"
                   enableDeleteByExample="false"
                   enableSelectByExample="false"
                   selectByExampleQueryId="false"/>
        </context>
</generatorConfiguration>

2.1 接口工程

MyBatis逆向工程生成的实体bean。

package com.szh.springboot.entity;
 
import java.io.Serializable;
 
public class Student implements Serializable {
 
    private Integer id;
 
    private String name;
 
    private Integer age;
 
    //getter and setter
}

接口服务,其中有两个方法。

package com.szh.springboot.service;
 
import com.szh.springboot.entity.Student;
 
/**
 *
 */
public interface StudentService {
 
    Student queryStudentById(Integer id);
 
    Integer queryAllStudentCount();
}

2.2 服务提供者

SpringBoot核心配置文件

# 配置内嵌tomcat端口号和上下文根
server.port=8081
server.servlet.context-path=/
 
# 设置连接数据库的信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=12345678
 
# 设置dubbo
spring.application.name=015-springboot-ssm-dubbo-provider
spring.dubbo.server=true
spring.dubbo.registry=zookeeper://localhost:2181
 
# 设置redis
spring.redis.host=localhost
spring.redis.port=6379

MyBatis逆向工程生成的dao接口和对应的mapper映射文件(这里就做一个简单的案例,所以只用到了 selectByPrimaryKey、queryAllStudentCount 这两个方法)

package com.szh.springboot.mapper;
 
import com.szh.springboot.entity.Student;
 
public interface StudentMapper {
 
    int deleteByPrimaryKey(Integer id);
 
    int insert(Student record);
 
    int insertSelective(Student record);
 
    Student selectByPrimaryKey(Integer id);
 
    int updateByPrimaryKeySelective(Student record);
 
    int updateByPrimaryKey(Student record);
 
    Integer queryAllStudentCount();
 
}
<?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.szh.springboot.mapper.StudentMapper">
 
  <resultMap id="BaseResultMap" type="com.szh.springboot.entity.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 t_student
    where id = #{id,jdbcType=INTEGER}
  </select>
 
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_student
    where id = #{id,jdbcType=INTEGER}
  </delete>
 
  <insert id="insert" parameterType="com.szh.springboot.entity.Student">
    insert into t_student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
 
  <insert id="insertSelective" parameterType="com.szh.springboot.entity.Student">
    insert into t_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.szh.springboot.entity.Student">
    update t_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.szh.springboot.entity.Student">
    update t_student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
 
  <select id="queryAllStudentCount" resultType="java.lang.Integer">
    select count(*)
    from t_student
  </select>
</mapper>

对接口工程中接口方法的实现,其中包括注入数据库持久层、注入redis模板类对象。

package com.szh.springboot.service.impl;
 
import com.alibaba.dubbo.config.annotation.Service;
import com.szh.springboot.entity.Student;
import com.szh.springboot.mapper.StudentMapper;
import com.szh.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
import java.util.concurrent.TimeUnit;
 
/**
 *
 */
@Component
@Service(interfaceClass = StudentService.class,version = "1.0.0",timeout = 15000)
public class StudentServiceImpl implements StudentService {
 
    @Autowired
    private StudentMapper studentMapper;
 
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
 
    @Override
    public Student queryStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }
 
    @Override
    public Integer queryAllStudentCount() {
 
        //首先去redis缓存中查询,如果有:直接使用;如果没有,去数据库中查询并存放到redis缓存中
        Integer allStudentCount= (Integer) redisTemplate.opsForValue().get("allStudentCount");
 
        //判断是否有值
        if (allStudentCount==null) {
            //此时为空,则去数据库中查询
            allStudentCount=studentMapper.queryAllStudentCount();
            //并存放到redis缓存中
            redisTemplate.opsForValue().set("allStudentCount",allStudentCount,30, TimeUnit.SECONDS);
        }
        return allStudentCount;
    }
 
}

pom文件

 <dependencies>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.4</version>
        </dependency>
 
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
 
        <!-- 接口工程 -->
        <dependency>
            <groupId>com.szh.springboot</groupId>
            <artifactId>014-springboot-ssm-dubbo-interface</artifactId>
            <version>1.0.0</version>
        </dependency>
 
    </dependencies>
 
    <build>
 
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
 
        <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>
    </build>

SpringBoot项目启动入口类

package com.szh.springboot;
 
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan(basePackages = "com.szh.springboot.mapper")
@EnableDubboConfiguration
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
 
}

2.3 服务消费者

SpringBoot核心配置文件

# 配置内嵌tomcat端口号和上下文根
server.port=8080
server.servlet.context-path=/
 
# 设置dubbo
spring.application.name=016-springboot-ssm-dubbo-consumer
spring.dubbo.registry=zookeeper://localhost:2181
 
# 配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

定义控制层,其中有两个请求方法

package com.szh.springboot.controller;
 
import com.alibaba.dubbo.config.annotation.Reference;
import com.szh.springboot.entity.Student;
import com.szh.springboot.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
/**
 *
 */
@Controller
public class StudentController {
 
    @Reference(interfaceClass = StudentService.class,version = "1.0.0",check = false)
    private StudentService studentService;
 
    @RequestMapping(value = "/student/detail/{id}")
    public String studentDetail(@PathVariable("id") Integer id,
                                Model model) {
        Student student=studentService.queryStudentById(id);
        model.addAttribute("student",student);
        return "studentDetail";
    }
 
    @GetMapping(value = "/student/all/count")
    public @ResponseBody Object allStudentCount() {
        Integer allStudentCount=studentService.queryAllStudentCount();
        return "学生总人数为:" + allStudentCount;
    }
 
}

pom文件

 <dependencies>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.4</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
 
        <!-- 接口工程 -->
        <dependency>
            <groupId>com.szh.springboot</groupId>
            <artifactId>014-springboot-ssm-dubbo-interface</artifactId>
            <version>1.0.0</version>
        </dependency>
 
    </dependencies>
 
    <build>
 
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>*.*</include>
                </includes>
            </resource>
        </resources>
 
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

响应的jsp页面、SpringBoot项目启动入口类

<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>$</title>
</head>
<body>
    <h3>学生信息</h3>
    <div>学生编号:${student.id}</div>
    <div>学生姓名:${student.name}</div>
    <div>学生年龄:${student.age}</div>
</body>
</html>
package com.szh.springboot;
 
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@EnableDubboConfiguration
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
 
}

2.4 启动测试!!!

因为我们这个案例是SpringBoot集成SSM、Dubbo、Redis、JSP,同时使用注册中心。所以启动的步骤是:

测试结果中,可以看到,第一个请求结果拿到了学生信息,第二个请求结果也查询出了学生数量,而且我们开启redis服务之后,可以看到发起第二个请求之后,redis缓存中已经有了这个 allStudentCount 数据,经过30秒之后,这个数据会被清除。

加载全部内容

相关教程
猜你喜欢
用户评论