在Ubuntu上搭建Java微服务架构涉及多个步骤,包括环境搭建、选择Java框架、创建微服务、服务发现和注册、配置管理等。以下是一个详细的指南:
sudo apt update
sudo apt install openjdk-11-jdk
验证安装:
java -version
sudo apt install maven
验证安装:
mvn -version
curl -fsSL https://get.docker.com | sh
sudo systemctl enable --now docker
验证安装:
docker --version
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
常用的Java框架包括Spring Boot和Spring Cloud,它们提供了服务发现、负载均衡、配置管理等功能。
pom.xml
文件中添加Spring Cloud依赖项。application.properties
文件中配置Eureka客户端。@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
配置文件application.yml
:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
添加依赖项:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件application.properties
:
spring.application.name=my-service-provider
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
创建服务接口和实现:
@RestController
@RequestMapping("/api/v1/hello")
public class HelloController {
@GetMapping
public String sayHello() {
return "Hello from my-service-provider!";
}
}
使用Eureka进行服务发现和注册。
创建Dockerfile:
FROM openjdk:11-jdk-alpine
WORKDIR /app
COPY target/your-microservice.jar /app/your-microservice.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/your-microservice.jar"]
构建Docker镜像:
docker build -t yourusername/your-microservice:tag .
运行Docker容器:
docker run -d -p 8080:8080 yourusername/your-microservice:tag
创建deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-service
spec:
replicas: 3
selector:
matchLabels:
app: my-service
template:
metadata:
labels:
app: my-service
spec:
containers:
- name: my-service
image: my-service:1.0
ports:
- containerPort: 8080
创建service.yaml
:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-service
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer
部署到Kubernetes集群:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
使用Spring Boot Actuator、Prometheus、Grafana等工具进行服务监控。