5、在启动类上加注解
(1)@SpringBootApplication 启动类注解
(2)@EnableDubbo dubbo注解
(3)@MapperScan("com.bdqn.doubbleuserprovider.mapper")该注解指向mapper包,没有或者错误会报:我也是踩了。
//Field ud in com.bdqn.doubbleuserprovider.service.UserServiceImpl // required a bean of type 'com.bdqn.doubbleuserprovider.mapper.UserDao' that could not be found.
6、在pom文件中,还需要进一步的配置,在build内部加资源配置:
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.html</include> <include>**/*</include> </includes> <filtering>false</filtering> </resource> </resources>
否则会报下面错误:
Invalid bound statement (not found):
三、消费者操作
1、由于消费者不需要操作数据库,所有只需要引入dubbo,web和公共组件即可。与provider的依赖一致。
2、配置文件application.properties中,这次扫描service中的实现类,因为在其中使用@Reference引用服务。
server.port=8089 dubbo.protocol.port = 20880 dubbo.application.name=dubbo-consumer dubbo.scan.base-packages=com.bdqn.mycustomer.service.impl dubbo.registry.address=zookeeper://127.0.0.1:2181
3、在service层中,创建customer接口与common中的接口对应。
public interface UserConsumerService { public String getUserNameByUid(int uid); }
4、实现service接口,在service的impl中创建。
(1)service注解来自spring框架
(2)@Reference来自dubbo,引用服务来自公共组件common。
@Service public class UserConsumerServiceImpl implements UserConsumerService { @Reference UserService us; @Override public String getUserNameByUid(int uid) { return us.getUserNameByUid(uid); } }
5、controller层,请求调用
(1)返回json格式的内容
@RestController public class UserController { @Autowired UserConsumerService service; @RequestMapping(value = "getuser/{uid}",method = RequestMethod.GET) public String getUserNameByUid(@PathVariable("uid") String uid){ return service.getUserNameByUid(Integer.valueOf(uid)); } }
(2)如果要返回html视图,需要在provider项目中加thymeleaf依赖。因为它是内容提供者。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
(3)同时在内容提供者的html文件中加声明。
<html lang="en" xmlns:th="http://www.thymeleaf.org">
四、结果展示
打开浏览器,访问地址就得到了结果。