当前位置: 首页 > 图灵资讯 > 技术篇> dubbo-redis练习

dubbo-redis练习

来源:图灵教育
时间:2023-06-17 13:55:13

1.注册学生项目需求1351.1

phone必须是唯一的,如果手机号码已经存在,注册失败

intaddstudent(Studentstudent);

返回值int

1:注册成功

2:手机号码已经存在

name至少有两个字符,age必须大于0

1.2查询学生

根据id查询,这个学生

先去redis查询学生。如果redis没有这个学生,请从数据库中查看,并将查询到的学生放在redis中。后来,学生应该从redis中获得它

StudentqueryStudent(Integerid);

1.3使用Dubbo框架

addStudent,querystudent是由服务提供商实现的,消费者可以是controller,调用提供商的两种方法,实现注册和查询

1.4页面使用html和ajax,jquery

form注册学生在html页面上提供,文本输入id用于查询,ajax技术用于注册和查询

html,query.将js放入resources/static目录中

2.公共资源内容资源接口135

创建普通maven项目course19

student实体类
package com.bjpowernode.model;import java.io.Serializable;//实体类  135public class Student implements Serializable {    ///序列化后添加脚本号    private static final long serialVersionUID = 1901229007746699151L;    private Integer id;    private String name;    private String phone;    private Integer age;    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", name='" + name + '\'' +                ", phone='" + phone + '\'' +                ", age=" + age +                '}';    }    public Student() {    }    public Student(Integer id, String name, String phone, Integer age) {        this.id = id;        this.name = name;        this.phone = phone;        this.age = age;    }    public static Student defaultStudent(){        Student student = new Student();        student.setId(0);        student.setName("-");        student.setPhone("-");        return student;    }    public static long getSerialVersionUID() {        return serialVersionUID;    }    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 String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}
StudentServicent资源接口
package com.bjpowernode.service;import com.bjpowernode.model.Student;////定义Dubbo接口资源  135public interface StudentService {    //添加    int addStudent(Student student);    //查询    Student queryStudent(Integer id);}
3.提供者135

创建springbot项目,访问mysql驱动,mybatis框架,redis

pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.7.12</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>com.bjpowernode</groupId>    <artifactId>course19_</artifactId>    <version>1.0.0</version>    <properties>        <java.version>1.8</java.version>    </properties>    <dependencies>        <!--依赖dubbo  135-->        <dependency>            <groupId>org.apache.dubbo</groupId>            <artifactId>dubbo-spring-boot-starter</artifactId>            <version>2.7.8</version>        </dependency>        <!--zookeper依赖于-->        <dependency>            <groupId>org.apache.dubbo</groupId>            <artifactId>dubbo-dependencies-zookeeper</artifactId>            <version>2.7.8</version>            <type>pom</type>            <!--排除重复log4j依赖-->            <exclusions>                <exclusion>                    <artifactId>slf4j-log4j12</artifactId>                    <groupId>org.slf4j</groupId>                </exclusion>            </exclusions>        </dependency>        <!--依赖jackson  136-->        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>2.11.4</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.datatype</groupId>            <artifactId>jackson-datatype-jsr310</artifactId>            <version>2.11.4</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.datatype</groupId>            <artifactId>jackson-datatype-jdk8</artifactId>            <version>2.11.4</version>        </dependency>        <!--依赖公共资源界面-->        <dependency>            <groupId>com.bjpowewrnode</groupId>            <artifactId>course19</artifactId>            <version>1.0.0</version>        </dependency>        <!--redis开始依赖  135-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>    <!--依赖mybatis-->        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>2.3.1</version>        </dependency>    <!--mybatis驱动-->        <dependency>            <groupId>com.mysql</groupId>            <artifactId>mysql-connector-j</artifactId>            <scope>runtime</scope>        </dependency>    <!--测试-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>
实现StudentServiceimpleimple实现资源接口
package com.bjpowernode.demo.service.impl;import com.bjpowernode.model.Student;import com.bjpowernode.service.StudentService;//提供者 实现公共资源接口类  135public class StudentServiceImpl implements StudentService {    //添加方法    //1 添加成功    //2 手机号码已经存在    @Override    public int addStudent(Student student) {        return 0;    }    @Override    public Student queryStudent(Integer id) {        return null;    }}
application.properties
# 配置dubo  135spring.application.name=studentservice-providerdubbo.scan.base-packages=com.bjpowernode.demo.servicedubbo.registry.address=zookeeper://localhost:2181#redispring配置.redis.host=localhostspring.redis.port=6379#密码#spring.redis.password=123#配置mybatismybatistististis.mapper-locations=classpath:mapper/*.xmlmybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl#数据源 datasourcespring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8spring.datasource.username=rootspring.datasource.password=lzl
dao接口
package com.bjpowernode.demo.dao;import com.bjpowernode.model.Student;import org.apache.ibatis.annotations.Param;//持久层 类框架的实现将有助于我们实现 135public interface StudentDao {    //按手机号查询    Student selectByPhone(@Param("phone")String phone);    ///添加数据    int insertStudent(Student student);}
mapper目录mybatis的sql映射文件Studentdaoo.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.bjpowernode.demo.dao.StudentDao"><!--    sql映射文件mybatis   -->    <!--按手机号查询  135  -->    <select id="selectByPhone" resultType="com.bjpowernode.model.Student">        select * from student2 where phone=#{phone}    </select>    <!--添加数据  135-->    <insert id="insertStudent">        insert  into student2(name,phone,age) values(#{name},#{phone},#{age})    </insert></mapper>
StudentServiceImple实现公共资源接口

 

package com.bjpowernode.demo.service.impl;import com.bjpowernode.demo.dao.StudentDao;import com.bjpowernode.model.Student;import com.bjpowernode.service.StudentService;import org.apache.dubbo.config.annotation.DubboService;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import javax.annotation.Resource;//提供者 实现公共资源接口类  135///暴露dubo的服务@DubboService(interfaceClass = StudentService.class,version = "1.0",timeout = 5000)public class StudentServiceImpl implements StudentService {    @Resource    private StudentDao studentDao;    ////声明redis模板对象  136    @Resource    private RedisTemplate redisTemplate;    //添加方法  135    //1 添加成功    //2 手机号码已经存在    //3 没有手机号    @Override    public int addStudent(Student student) {        int result = 0;        ///查询手机号码是否唯一        if(student.getPhone()!=null){            Student stu = studentDao.selectByPhone(student.getPhone());            if(stu!=null){//手机号码已经存在                result=2;            }else {//手机号码不存在。添加处理                //添加处理                result=studentDao.insertStudent(student);            }        }else {            result=3;        }        return result;    }    ///查询功能  136    @Override    public Student queryStudent(Integer id) {        ////从redis查询Student使用json存储对象        ///设置key的序列化方法是String        redisTemplate.setKeySerializer(new StringRedisSerializer());        ///设置value的序列化方法是json        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));        final String USER_KEY="STUDENT:";        Student student=null;        //首先在redis中查询 id        if(id!=null){            ///id的样子  STUDENT:1001            String key = USER_KEY + id;            student = (Student) redisTemplate.opsForValue().get(USER_KEY + id);            System.out.println(id+“从redis查询数据”+student);            if (student==null) {//redis中没有发现,student为空,将此数据添加到redis中                ///从数据库中查看                student = studentDao.selectById(id);                System.out.println(id+“从数据库中查询数据”+student);                if(student!=null){///数据库中发现的不是空的                    //存入redis                    redisTemplate.opsForValue().set(key,student);                }else {                    没有数据库                    ///如果redis和数据库中没有,就会出现缓存穿透问题                    //解决缓存穿透问题,在rediss中存储Student中定义的默认数据                    redisTemplate.opsForValue().set(key,Student.defaultStudent());                }            }        }        return student;    }}
Course191Aplication提供商的主启动
package com.bjpowernode;import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@EnableDubbo ///启动dubo@MapperScan(basePackages = "com.bjpowernode.demo.dao)//为了实现dao接口publicc class course191aplication {    public static void main(String[] args) {        SpringApplication.run(course191aplication.class, args);    }}

 

4.消费者136
创建springboot项目天界web依赖

dubbo-redis练习_xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.7.12</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>com.bjpowernode</groupId>    <artifactId>course19_2</artifactId>    <version>1.0.0</version>    <properties>        <java.version>1.8</java.version>    </properties>    <dependencies>        <!--依赖dubbo  136-->        <dependency>            <groupId>org.apache.dubbo</groupId>            <artifactId>dubbo-spring-boot-starter</artifactId>            <version>2.7.8</version>        </dependency>        <!--zookeper依赖于-->        <dependency>            <groupId>org.apache.dubbo</groupId>            <artifactId>dubbo-dependencies-zookeeper</artifactId>            <version>2.7.8</version>            <type>pom</type>            <!--排除重复log4j依赖-->            <exclusions>                <exclusion>                    <artifactId>slf4j-log4j12</artifactId>                    <groupId>org.slf4j</groupId>                </exclusion>            </exclusions>        </dependency>        <!--依赖公共资源界面-->        <dependency>            <groupId>com.bjpowewrnode</groupId>            <artifactId>course19</artifactId>            <version>1.0.0</version>        </dependency>        <!--web依赖-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>
application.properties
#指定端口号server.port=9001server.servlet.context-path=/demo#dubbospring.application.name=demo-consumerdubbo.registry.address=zookeeper://localhost:2181dubbo.scan.base-packages=com.bjpowernode.democonsumer
Dubococontrolerler
package com.bjpowernode.democonsumer.controller;import com.bjpowernode.model.Student;import com.bjpowernode.service.StudentService;import org.apache.dubbo.config.annotation.DubboReference;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;//消费者  136@RestControllerpublic class DubboController {    @DubboReference(interfaceClass = StudentService.class,version = "1.0")    private StudentService studentService;    @PostMapping("/student/add")    public String addStudent(Student student){        ///处理student的数据,name需要有值,phone,age必须有值        int result = studentService.addStudent(student);        String msg = “请稍后处理”;        if(result==1){            msg = “加学生:”+student.getName()+",成功";        }else if(result==2){            msg=student.getPhone()+”,这个手机号码已经注册,请更换手机号“请更换手机号”;        }else{            msg=“手机号码为空”;        }        return “消费者添加学生的结果:”+msg;    }}
Course192aplication消费者主动启动
package com.bjpowernode;import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@EnableDubbopublic class course192aplication {    public static void main(String[] args) {        SpringApplication.run(course192aplication.class, args);    }}

添加功能的初步测试

dubbo-redis练习_xml_02

继续完成查询功能

Dubococontrolerler
package com.bjpowernode.democonsumer.controller;import com.bjpowernode.model.Student;import com.bjpowernode.service.StudentService;import org.apache.dubbo.config.annotation.DubboReference;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;//消费者  136@RestControllerpublic class DubboController {    @DubboReference(interfaceClass = StudentService.class,version = "1.0")    private StudentService studentService;    //增加学生    @PostMapping("/student/add")    public String addStudent(Student student){        ///处理student的数据,name需要有值,phone,age必须有值        int result = studentService.addStudent(student);        String msg = “请稍后处理”;        if(result==1){            msg = “加学生:”+student.getName()+",成功";        }else if(result==2){            msg=student.getPhone()+”,这个手机号码已经注册,请更换手机号“请更换手机号”;        }else{            msg=“手机号码为空”;        }        return “消费者添加学生的结果:”+msg;    }    ///查询学生  136    @GetMapping("/student/query")    public String queryStudent(Integer id){        String msg = "";        Student student=null;        if(id !=null && id>0){           student = studentService.queryStudent(id);           if(student!=null){               msg = “查询学生信息:”+student.toString();           }else{               msg=“没有发现”;           }        }else {            msg = 查询的id不正确”;        }        return msg;    }}

 

dubbo-redis练习_Dubbo_03

5.写查询页面1344static目录下的html目录Query.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>查询学生  134</title>    <!--引入js库  134-->    <script type="text/javascript" src="js/jquery-3.4.1.js"></script></head>    <input type="text" id="stuId" value=""/><br>    <button id="btn">查询</button><br></body>    <script type="text/javascript">        $(function (){            $("#btn").click(function (){                var stuId = $("#stuId").val();               $.ajax({                   url:"/demo/student/query",                   type:"get",                   //data:"id="+stuId,                   data:{id:stuId},                   dataType:"text",                   success:function (data){                       alert(data);                   }               })            })        })    </script></html>

 

dubbo-redis练习_spring_04