最近学完了springboot,集成了dubbo,利用Redis做缓存,实现分布式远程接口调用。
这里用的是zookeeper作为注册中心,并部署在Linux系统上。
项目结构图:
- spring-boot-interface是公共接口模块
- spring-boot-provider是服务的提供者模块
- spring-boot-consumer是服务的消费者模块
1.公共接口模块
写个接口和相关的类,然后再经过maven的install打包到本地库,就可以给其他项目使用了。
2.服务提供者模块
- StudentMapper
@Mapper
public interface StudentMapper {
Student selectByPrimaryKey(Integer id);
List<Student> selectAllStudent();
}
- StudentServiceImpl
@Component
@Service(version = "1.0.0", timeout = 10000)//dubbo注解
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Autowired
private RedisTemplate<Object,Object> redisTemplate;
@Override
public Student getStudent(int id) {
return studentMapper.selectByPrimaryKey(id);
}
@Override
public List<Student> getAllStudents() {
List<Student> students = (List<Student>) redisTemplate.opsForValue().get("students");
if (students == null){
students = studentMapper.selectAllStudent();
System.out.println("数据库查询");
redisTemplate.opsForValue().set("students",students);
}else {
System.out.println("缓存查询");
}
return students;
}
}
- Application
@SpringBootApplication
@EnableDubboConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- application.properties
#WEB\u670D\u52A1\u7AEF\u53E3
server.port=8080
#dubbo\u914D\u7F6E
spring.dubbo.appname=springboot-dubbo-provider
spring.dubbo.registry=zookeeper://192.168.137.129:2181
mybatis.mapper-locations=classpath:mapper/*.xml
#\u914D\u7F6E\u6570\u636E\u5E93\u8FDE\u63A5\u4FE1\u606F
spring.datasource.url=jdbc:mysql://localhost:3306/ssm_curd?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#配置redis连接信息
spring.redis.host=192.168.137.129
spring.redis.port=6379
spring.redis.password=root
然后在pom文件引入相应的jar包,就可以完成服务生产者模块。
3.服务消费者模块
- StudentController
@RestController
public class StudentController {
@Reference(version = "1.0.0", timeout = 10000)
private StudentService studentService;
@RequestMapping("/boot/student")
public Object getStudent(@RequestParam("id") Integer id){
return studentService.getStudent(id);
}
@RequestMapping("/boot/students")
public List<Student> getStudents(){
return studentService.getAllStudents();
}
}
- application.properties
server.port=9090
spring.dubbo.appname=springboot-dubbo-provider
spring.dubbo.registry=zookeeper://192.168.137.129:2181
在pom中引入相应的jar包,完成服务消费者。
4.启动虚拟机里的Redis和zookeeper
5.分别启动服务提供者和消费者
测试相应接口
至此,完成springboot集成dubbo以及用Redis做缓存简单的实现。