工具:IDEA2018.3
环境:jdk8+windows10+maven3.5
框架:springCloud
1.file------>>new-------->>project
2.
然后一路next,最后点击finsh;
在此我就不一步步讲解操作步骤了,直接上成品,然后细说;
1.eureka(注册中心)
2.ribbon(负载均衡)
3.feign(声明式服务调用)
第一步:
右键项目名称 new------------>>module
2.
3.
点击next,最后点击finsh;
4.将application.properties文件修改成(application.yml),加入如下代码:
server:
port: 8080
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
5.在启动入口类 EurekaApplication中加入 @EnableEurekaServer注解,然后启动,成功返回如下界面:
ribbon(负载均衡)
1.2步同上!!!
3.
4.将application.properties文件修改成(application.yml),加入如下代码:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8080/eureka/
server:
port: 8081
spring:
application:
name: ribbon-provider
注意:port不能出现重复;
5.写一个service和controller
service代码如下:
@Service
public class HelloService {
public String sayHello(){
return "helloWorld"; // 提供一个hello World
}
}
controller代码如下:
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String sayHello(String name){
return helloService.sayHello() + " " + name;
}
}
6.启动类RibbonApplication修改成如下代码:
@LoadBalanced该注解为开启负载均衡
@SpringBootApplication
@EnableDiscoveryClient //注册服务
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
启动该子项目,成功注册中心会出现如下情况:
feign(声明式服务调用)
1,2步骤同上
3.
点击完成;
4步骤同上port接口:8082;
5.写一个rpc /service和controller
rpc代码如下:
@FeignClient(value = "ribbon-provider")
public interface GetHello {
@RequestMapping(value = "/hello?name=feign",method = RequestMethod.GET)
public String sayHello();
}
service代码如下:
@Service
public class HelloService {
@Autowired
private GetHello getHello;
public String sayHello(){
return getHello.sayHello();
}
}
controller代码如下:
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String sayHello(String name){
return helloService.sayHello() + " " + name;
}
}
6.启动类FeignApplication修改成如下代码:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
7.启动feign子项目,出现如下情况:
启动成功;
到此一个简单的maven+springCloud项目就搭建完成了;
源码下载地址: https://pan.baidu.com/s/1MowmriEy2bnujF2s94oWZg 提取码:8swh
原创不易,转载请注明出处;