springboot(二)

springboot 集成 redis

1. 通过Mybatis逆向工程生成实体bean和数据持久层

逆向工程相关文件:GeneratorMapper.xml,这个文件放的位置与src同级。编译这个文件需要的插件在第二步pom.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="E:\mysql-connector-java-5.1.38.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://192.168.132.40:3306/springboot"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- 生成 model 类,targetPackage 指定 model 类的包名, targetProject 指
        定生成的 model 放在 eclipse 的哪个工程下面-->
        <javaModelGenerator targetPackage="com.wkcto.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.wkcto.springboot.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的
        包名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wkcto.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>

生成mapper文件包括StudentMapper.xml和StudentMapper.java:2个插入,2个更新,1个查询,1个删除方法

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

Student.java

public class Student {
    private Integer id;
    private String name;
    private Integer age;
	//会成成set/get方法,此处略
}

2. 依赖文件pom.xml添加redis依赖

    <dependencies>
    	<!-- springbootd的web起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		<!-- mybatis集成springboot起步依赖和jdbc驱动 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
		<!-- 可能使用到的工具类:StringUtils,ObjectUtils等 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
        	<!-- 使项目加载mapper.xml,这一条没有,会出现bindException:找不到方法 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!-- 因为重新声明加载xml文件,所以主配置文件需要重新设置加载 -->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <!-- mybatis逆向工程插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

3. 核心配置文件application.properties

#注意这里的驱动有所不同
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置数据库地址,?后面解决字符乱码问题
spring.datasource.url=jdbc:mysql://数据库所在IP地址:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

#redis主机地址
spring.redis.host=redis服务启动所在主机IP
#默认端口6379
spring.redis.port=6379
#密码在配置文件中查看
spring.redis.password=123456

4. 启动redis服务

Linux启动redis服务

  1. 切换root用户 su root 回车,输入密码
  2. 使用cd 命令切换到redis安装目录下的src文件夹中
  3. ./redis-server …/redis.conf & 启动redis服务,并保证后台运行(&是后台运行的意思)

5. 控制器RedisController类

@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/student/count")
    public @ResponseBody Object allcount() {
        int i = studentService.getCount();
        return "学生人数" + i;
    }
}

6. 服务接口StudentService

public interface StudentService {
    int getCount();
}

7. 接口实现类StudentServiceImpl

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    //声明redis模板对象
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    
    @Override
    public int getCount() {
        //通过redis模板对象从redis 中取值
        Integer allStudentCount = (Integer) redisTemplate.opsForValue().get("allStudentCount");
        if (!ObjectUtils.allNotNull(allStudentCount)) {
            //查找数据库
            allStudentCount= studentMapper.selectAllStudentCount();
            redisTemplate.opsForValue().set("allStudentCount", allStudentCount,30, TimeUnit.SECONDS);
        }
        return allStudentCount;
    }
}

8. StudentMapper

StudentMapper.xml 添加selectAllStudentCount方法

  <select id="selectAllStudentCount" resultType="Integer">
    select count(*) from t_student
  </select>

StudentMapper.java 添加selectAllStudentCount方法

public interface StudentMapper{
	Integer selectAllStudentCount();
}

9. 启动类Application.java

@SpringBootApplication
@MapperScan("com.wkcto.springboot.mapper") //扫描mapper文件
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

10. 运行:

在地址栏输入localhost:8080/student/count
页面显示:学生人数8

springboot 集成 dubbo

需要一个接口工程,一个服务提供者,一个消费者
备注:下面web项目中依赖都省略了

<!-- 这是web项目自动添加的web起步依赖 -- >
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

接口工程

这个工程就是一个java项目,只放公共的接口或公共model类,实现类在服务提供者中写

public interface StudentService {
    Integer queryAll();
}

服务提供者

实现具体要提供的服务,即实现接口
具体步骤:

  1. 依赖中需要添加接口工程,添加dubbo起步依赖和dubbo注册中心依赖
	<!-- dubbo起步依赖 -->
	<dependency>
        <groupId>com.alibaba.spring.boot</groupId>
        <artifactId>dubbo-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>
    <!-- 注册中心依赖 -->
    <dependency>
        <groupId>com.101tec</groupId>
        <artifactId>zkclient</artifactId>
        <version>0.10</version>
    </dependency>
	<!-- 接口工程 -->
    <dependency>
        <groupId>com.wkkcto.springboot</groupId>
        <artifactId>017-springboot-dubbo-interface</artifactId>
        <version>1.0.0</version>
    </dependency>
  1. 需要在主配置文件中配置dubbo信息
server.port=8090
server.servlet.context-path=/provider

#dubbo服务名称
spring.application.name=springboot-dubbo-provider
#设置当前工程为服务提供者
spring.dubbo.server=true
#设置注册中心,如果不是本地开启zookeeper服务,就将localhost改成zookeeper所在IP
spring.dubbo.registry=zookeeper://localhost:2181
  1. service层实现类要使用dubbo的service注解@Service。光标放在@Service注解上面,按ctrl+p可以查看参数信息,interfaceClass是需要实现的接口(来自接口工程),version 设置实现类版本号,timeout表示超时时间
    注意:
    这里的@Service很容易引用springframework的注解,一定注意
@Component
@Service(interfaceClass = StudentService.class,version = "1.0.0" ,timeout = 15000)
public class StudentServiceImpl implements StudentService {
    @Override
    public Integer queryAll() {

        return 10;
    }
}
  1. 服务启动类Application.java,需要在类名上面加上@EnableDubboConfiguration注解,否则spring扫描不到dubbo的@Service注解
@SpringBootApplication
@EnableDubboConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

消费者

具体步骤:

  1. 这里使用的依赖文件和服务提供者一样pom.xml,如果需要mybatis依赖需再添加mybatis起步依赖和mysql驱动依赖
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>
        <!-- 接口工程 -->
        <dependency>
            <groupId>com.wkkcto.springboot</groupId>
            <artifactId>017-springboot-dubbo-interface</artifactId>
            <version>1.0.0</version>
        </dependency>
  1. 主配置文件application.properties 设置服务名称和注册中心
server.port=8080
server.servlet.context-path=/consumer
#dubbo服务工程名称
spring.application.name=springboot-dubbo-consumer
#这里不需要设置当前工程为服务提供者
#设置注册中心
spring.dubbo.registry=zookeeper://192.168.132.40:2181
  1. 控制器Controller,这里不能使用@Autowird自动注入,应该使用dubbo的注解@Reference,参数声明接口和版本表示使用的哪个实现类,check表示检查服务,开发时设置false表示不检查,默认检查
    注意:@Reference有两个,这里一定使用dubbo的注解
@RestController
public class StudentController {

    @Reference(interfaceClass = StudentService.class,version = "1.0.0",check = false)
    private StudentService studentService;

    @RequestMapping("/count")
    public String studentCount() {
        Integer integer = studentService.queryAll();
        return "学生人数" + integer;
    }
}
  1. 先保证已经开启zookeeper服务(在安装路径下bin文件夹,windows环境:zkServer.cmd双击;Linux环境:当前bin目录下执行 ./zkServer.sh start),再启动服务类Application.java,通过@EnableDubboConfiguration 来扫描dubbo的注解
@SpringBootApplication
@EnableDubboConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

springboot 集成 ssm、redis、dubbo

1. 接口工程

model文件,实体类,这里的model类是通过代码生成器生成,具体生成器代码在服务提供者工程中查看

public class Student implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
	//这里还有set/get方法,这里省略了
}

service接口,公共接口,实现类在服务提供者工程中实现

public interface StudentService {
    Student queryById(Integer id);
    Integer queryAll();
}

2. 服务提供者

  1. 依赖文件pom.xml,需要集成ssm(mybatis要2个),redis(1个),dubbo(2个),同时还有接口项目
<dependencies>
        <!-- mybatis起步依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- mysql数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- redis起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- dubbo起步依赖 -->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- 注册中心 -->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
            <!-- exclusions表示排除,这里使用是因为zkclient中有日志jar,排除这两个jar包,解决服务在启动时,控制台开头的警告信息 -->
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
		<!-- 接口工程 -->
        <dependency>
            <groupId>com.wkcto.springboot</groupId>
            <artifactId>020-springboot-ssm-dubbo-interface</artifactId>
            <version>1.0.0</version>
        </dependency>
		<!-- Apache提供的工具类 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
</dependencies>
    <build>
    	<!-- 使mapper.xml文件与主配置文件可以加载到项目中 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resource</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <!-- mybatis逆向工程插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!--配置文件的位置,在项目目录下:指与src同级目录-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  1. 主配置文件application.properties ,需要设置数据源,redis配置,dubbo配置
server.port=8081
server.servlet.context-path=/

#注意:这里的驱动有所不同
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#这里要将“IP地址”改成localhost或者数据库所在的地址;?后面是解决字符乱码问题
spring.datasource.url=jdbc:mysql://IP地址:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
#注意这里是username,不是name
spring.datasource.username=root
spring.datasource.password=123456

#redis所在主机IP
spring.redis.host=IP地址
#redis端口
spring.redis.port=6379
#redis的密码,可以在redis的配置文件中查看
spring.redis.password=123456

#设置dubbo当前的服务名称
spring.application.name=ssm-dubbo-provider
#设置当前项目是服务提供者
spring.dubbo.server=true
#设置注册中心,注册中心服务所在的IP地址
spring.dubbo.registry=zookeeper://IP地址:2181
  1. 代码生成器GeneratorMapper.xml
    1. 怎么找到JDBC 驱动?
      前提是有本地仓库(idea查看本地仓库:ctrl+alt+s ,搜索maven,点击maven,右侧最下方就是),找到本地仓库路径,依次找到mysql --> mysql-connector-java --> 版本号 -->驱动文件(就是jar包)
<?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.38.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://数据库所在IP地址:3306/springboot"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- 生成 model 类,targetPackage 指定 model 类的包名, targetProject 指
        定生成的 model 放在 eclipse 的哪个工程下面-->
        <javaModelGenerator targetPackage="com.wkcto.springboot.model"
                            targetProject="D:\ideaWorkspace\springboot-first\020-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 放在 eclipse 的哪个工程下面 -->
        <sqlMapGenerator targetPackage="com.wkcto.springboot.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的
        包名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wkcto.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>
  1. dao层mapper文件
    StudentMapper.xml,默认生成6个方法:2个insert,2个update,1个select,1个delete
<?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.wkcto.springboot.mapper.StudentMapper">
  <resultMap id="BaseResultMap" type="com.wkcto.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 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.wkcto.springboot.model.Student">
    insert into t_student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.wkcto.springboot.model.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.wkcto.springboot.model.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.wkcto.springboot.model.Student">
    update t_student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>

  <select id="selectAllk" resultType="java.lang.Integer">
    select count(*) from t_student
  </select>
</mapper>

StudentMapper.java,默认生成6个方法:2个insert,2个update,1个select,1个delete

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 selectAllk();
}
  1. service层实现类 StudentServiceImpl.java
    使用spring框架的@Component注解将当前类交给spring容器,@Service注解是dubbo的,指明当前类是哪个接口的实现类,并指明当前类的版本号,timeout 表示响应超时时间
@Component
@Service(interfaceClass = StudentService.class,version = "1.0.0" ,timeout = 15000)
public class StudentServiceImpl implements com.wkcto.springboot.service.StudentService {

    @Autowired
    private StudentMapper studentMapper;

	//这里使用redis模板对象
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public Student queryById(Integer id) {
        Student student = studentMapper.selectByPrimaryKey(id);
        return student;
    }

    @Override
    public Integer queryAll() {
    	//查询人数时,先从redis中获取,看是否为空,如果没有则再从数据库中查找
        Integer allStudentCount = (Integer) redisTemplate.opsForValue().get("allStudentCount");
        if (!ObjectUtils.allNotNull(allStudentCount)) {
            allStudentCount= studentMapper.selectAllk();
            redisTemplate.opsForValue().set("allStudentCount", allStudentCount,30, TimeUnit.SECONDS);
        }
        return allStudentCount;
    }
}
  1. 启动服务类Application.java,这里介绍一下四个注解
    @SpringBootApplication //默认在当前类启动服务
    @EnableDubboConfiguration //使spring可以识别dubbo注解
    @MapperScan(basePackages = “com.wkcto.springboot.mapper”) //扫描mapper接口文件,basePackage属性指明文件位置
    @EnableTransactionManagement //开启事务
@SpringBootApplication
@EnableDubboConfiguration
@MapperScan(basePackages = "com.wkcto.springboot.mapper")
@EnableTransactionManagement
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3. 消费者

  1. 依赖文件pom.xml,这里不需要操作数据库,所以没有mybatis,redis依赖
        <!-- dubbo起步依赖 -->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- 注册中心 -->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>
        <!-- 接口工程 -->
        <dependency>
            <groupId>com.wkcto.springboot</groupId>
            <artifactId>020-springboot-ssm-dubbo-interface</artifactId>
            <version>1.0.0</version>
        </dependency>
  1. 主配置文件application.properties
server.port=8080
server.servlet.context-path=/consumer

spring.application.name=ssm-dubbo-consumer
spring.dubbo.registry=zookeeper://192.168.132.40:2181
  1. controller层
    @Reference注解是dubbo的,使用这个注解来引入service,之前的@Service不能使用。通过@Reference中的interfaceClass和version来指定引入的接口和实现类是哪个,check是检查dubbo服务,false表示不检查,默认true
@RestController
public class StudentController {

    @Reference(interfaceClass = StudentService.class,version = "1.0.0",check = false)
    private StudentService studentService;

    @RequestMapping("/student/count")
    public String strudentCount() {
        Integer coung = studentService.queryAll();
        return "学生总人数:" + coung;
    }

    @RequestMapping("/student")
    public Student student(Integer id) {
        Student student = studentService.queryById(id);
        return student;
    }
}
  1. 启动服务类Application.java
@SpringBootApplication
@EnableDubboConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4. 服务启动步骤

以下服务在Linux上启动需要使用root用户,切换root用户命令:su root

  1. 启动mysql服务
    Linux启动mysql服务:使用cd 命令切换到mysql安装目录的bin文件夹下,使用命令 ./mysqld_safe & //后台启动mysql服务
  2. 启动redis服务
    Linux启动redis服务:使用cd 命令切换到redis安装目录的src文件夹下,使用命令 ./redis-server …/redis.conf & //后台启动redis服务
  3. 启动zookeeper服务
    Linux启动zookeeper服务:使用cd 命令切换到zookeeper安装目录的bin文件夹下,使用命令 ./zkServer.sh start //直接后台启动zookeeper服务,关闭命令:./zkServer.sh stop
  4. 启动服务提供者启动类
  5. 启动消费者启动类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值