Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor sample_cosmos.azure-spring-data-cosmos #187

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,86 +1,164 @@
# Azure Spring Boot Sample Cosmos Multi Database Multi Account for Java

## Key concepts
## Getting started
This guide demonstrates how to use Azure Cosmos DB via `azure-spring-data-cosmos` to store data in and retrieve data from your Azure Cosmos DB.

## What You Will Build
You will build an application to write data to and query data from Azure Cosmos DB via `azure-spring-data-cosmos`.

## What You Need

### Configure Cosmos Database
1. Log into <https://portal.azure.com>.
- [An Azure subscription](https://azure.microsoft.com/free/)
- [Terraform](https://www.terraform.io/)
- [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli)
- [JDK8](https://www.oracle.com/java/technologies/downloads/) or later
- Maven
- You can also import the code straight into your IDE:
- [IntelliJ IDEA](https://www.jetbrains.com/idea/download)

1. Click `Create a resource`.
## Provision Azure Resources Required to Run This Sample

1. Input `Azure Cosmos DB`.
### Authenticate Using the Azure CLI
Terraform must authenticate to Azure to create infrastructure.

1. Click `Azure Cosmos DB`
![Find Cosmos Resource 01](resource/creating-cosmos-01.png)
In your terminal, use the Azure CLI tool to setup your account permissions locally.

![Find Cosmos Resource 02](resource/creating-cosmos-02.png)
```shell
az login
```

Your browser window will open and you will be prompted to enter your Azure login credentials. After successful authentication, your terminal will display your subscription information. You do not need to save this output as it is saved in your system for Terraform to use.

```shell
You have logged in. Now let us find all the subscriptions to which you have access...

[
{
"cloudName": "AzureCloud",
"homeTenantId": "home-Tenant-Id",
"id": "subscription-id",
"isDefault": true,
"managedByTenants": [],
"name": "Subscription-Name",
"state": "Enabled",
"tenantId": "0envbwi39-TenantId",
"user": {
"name": "[email protected]",
"type": "user"
}
}
]
```

If you have more than one subscription, specify the subscription-id you want to use with command below:
```shell
az account set --subscription <your-subscription-id>
```

### Provision the Resources

After login Azure CLI with your account, now you can use the terraform script to create Azure Resources.

#### Run with Bash

```shell
# In the root directory of the sample
# Initialize your Terraform configuration
terraform -chdir=./terraform init

# Apply your Terraform Configuration
terraform -chdir=./terraform apply -auto-approve

```

#### Run with Powershell

```shell
# In the root directory of the sample
# Initialize your Terraform configuration
terraform -chdir=terraform init

1. Click **Create**.
# Apply your Terraform Configuration
terraform -chdir=terraform apply -auto-approve

![Create new Cosmos](resource/creating-cosmos-03.png)
```

1. On the **Create key vault** page, input `Subscription`, `Resource group`, `Account Name`, then click `Review + Create`.
It may take a few minutes to run the script. After successful running, you will see prompt information like below:

![Specify the options](resource/specify-the-options.png)
```shell

![Create Cosmos resource](resource/create-cosmos-resource.png)
random_password.mysql_login_password: Creating...
azurecaf_name.mysql_login_name: Creating...
azurecaf_name.cosmos_01: Creating...
azurecaf_name.mysql: Creating...
azurecaf_name.cosmos_02: Creating...
azurecaf_name.resource_group: Creating...
...
azurerm_cosmosdb_account.application_01: Creating...
azurerm_cosmosdb_account.application_02: Creating...
...
azurerm_cosmosdb_sql_database.db_01: Creating...
...
...
Apply complete! Resources: 14 added, 0 changed, 0 destroyed.

```

1. When complete, click `Go to resource`.
You can go to [Azure portal](https://ms.portal.azure.com/) in your web browser to check the resources you created.

![Go to resource](resource/go-to-resource.png)
### Export Output to Your Local Environment
Running the command below to export environment values:

1. Click **Keys** in the left navigation pane, copy your **URI**, the **PRIMARY KEY** and **SECONDARY KEY**;
#### Run with Bash

![Get Connect Info](resource/get-connect-info.png)
```shell
source ./terraform/setup_env.sh
```

1. Replace the content in `application.properties` with the obtained information.
#### Run with Powershell

1. We need to create another cosmos DB as the secondary like the steps above.
```shell
. terraform\setup_env.ps1
```

1. Add MYSQL connection attributes in `application.properties`.
## Run Locally

## Key concepts
## Examples
### Configure application.yml
```yaml
# primary account cosmos config
azure.cosmos.primary.uri=your-primary-cosmosDb-uri
azure.cosmos.primary.key=your-primary-cosmosDb-key
azure.cosmos.primary.secondary-key=your-primary-cosmosDb-secondary-key
azure.cosmos.primary.database=your-primary-cosmosDb-dbName
azure.cosmos.primary.populate-query-metrics=if-populate-query-metrics
In your terminal, run `mvn clean spring-boot:run`.

# secondary account cosmos config
azure.cosmos.secondary.uri=your-secondary-cosmosDb-uri
azure.cosmos.secondary.key=your-secondary-cosmosDb-key
azure.cosmos.secondary.secondary-key=your-secondary-cosmosDb-secondary-key
azure.cosmos.secondary.database=your-secondary-cosmosDb-dbName
azure.cosmos.secondary.populate-query-metrics=if-populate-query-metrics

#mysql connection attributes
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=your-mysql-username
spring.datasource.password=your-mysql-password
```shell
mvn clean spring-boot:run
```

### Run with Maven
## Verify This Sample

Verify in your app’s logs that similar messages were posted:
```shell
cd azure-spring-boot-samples/cosmos/azure-spring-data-cosmos/cosmos-multi-database-multi-account
mvn spring-boot:run
...
Data added successfully .........
...
Get secondaryCosmosUser 1024: [email protected] 1k Mars .........
```

Verify Result:
The corresponding data is added to the mysql database and cosmos database
The corresponding data is added to the mysql database and cosmos database
![Result in MYSQL](resource/result-in-mysql.png)
![Result in Primary Cosmos Database](resource/result-in-primary-cosmos-database.png)
![Result in Secondary Cosmos Database](resource/result-in-secondary-cosmos-database.png)

## Troubleshooting
## Next steps
## Contributing

<!-- LINKS -->
## Clean Up Resources
After running the sample, if you don't want to run the sample, remember to destroy the Azure resources you created to avoid unnecessary billing.

The terraform destroy command terminates resources managed by your Terraform project.
To destroy the resources you created.

#### Run with Bash

```shell
terraform -chdir=./terraform destroy -auto-approve
```

#### Run with Powershell

```shell
terraform -chdir=terraform destroy -auto-approve
```
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.cosmos.CosmosUserRepository;
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.mysql.MysqlUser;
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.mysql.MysqlUserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
Expand All @@ -22,6 +24,8 @@
@SpringBootApplication
public class MultiDatabaseApplication implements CommandLineRunner {

private static final Logger logger = LoggerFactory.getLogger(MultiDatabaseApplication.class);

@Autowired
private CosmosUserRepository cosmosUserRepository;

Expand Down Expand Up @@ -51,7 +55,7 @@ public void run(String... var1) throws Exception {
mysqlUserRepository.save(mysqlUser);
mysqlUserRepository.findAll().forEach(System.out::println);
CosmosUser secondaryCosmosUserGet = secondaryDatabaseTemplate.findById(CosmosUser.class.getSimpleName(), cosmosUser.getId(), CosmosUser.class);
System.out.println(secondaryCosmosUserGet);
logger.info("Get secondaryCosmosUser " + secondaryCosmosUserGet + " .........");
}


Expand All @@ -62,6 +66,7 @@ public void setup() {
// Same to this.cosmosUserRepository.save(user).block();
secondaryDatabaseTemplate.createContainerIfNotExists(userInfo);
secondaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName()));
logger.info("Data added successfully" + " .........");
}

@PreDestroy
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
azure:
cosmos:
primary:
uri: ${AZURE_COSMOS_URI_1}
key: ${AZURE_COSMOS_KEY_1}
secondary-key: ${AZURE_COSMOS_SECONDARY_KEY_1}
database: ${AZURE_COSMOS_DATABASE_1}
populate-query-metrics: if-populate-query-metrics
secondary:
uri: ${AZURE_COSMOS_URI_2}
key: ${AZURE_COSMOS_KEY_2}
secondary-key: ${AZURE_COSMOS_SECONDARY_KEY_2}
database: ${AZURE_COSMOS_DATABASE_2}
populate-query-metrics: if-populate-query-metrics
spring:
datasource:
username: ${AZURE_MYSQL_USERNAME}@${AZURE_MYSQL_HOST}
password: ${AZURE_MYSQL_PASSWORD}
url: jdbc:mysql://${AZURE_MYSQL_HOST}.mysql.database.azure.com:3306/db_example
jpa:
hibernate:
ddl-auto: update
Loading