浅谈将JAVA与Azure Redis配合使用

Cbits 2017-08-24 11:52:10
你可以使用 http://redis.io/clients 中列出的任何 Java 客户端来进行操作。这里就不一一列举了 。

检索主机名和访问密钥

若要连接到某个 Azure Redis 缓存实例,缓存客户端需要该缓存的主机名、端口和密钥。 在某些客户端中,这些项的名称可能略有不同。 可以在 Azure 门户中检索该信息,也可以通过命令行工具(例如 Azure CLI)来检索。
使用 Azure 门户检索主机名、端口和访问密钥
若要使用 Azure 门户检索主机名、端口和访问密钥,请浏览到 Azure 门户中的缓存, 然后在“资源”菜单中单击“访问密钥”和“属性”。

使用 Azure CLI 检索主机名、端口和访问密钥
若要使用 Azure CLI 2.0 检索主机名和端口,可调用 az redis show;若要检索密钥,可调用 az redis list-keys。 以下脚本调用这两个命令,并将主机名、端口和密钥回显到控制台。
Azure CLI
复制
#/bin/bash

# Retrieve the hostname, ports, and keys for contosoCache located in contosoGroup

# Retrieve the hostname and ports for an Azure Redis Cache instance
redis=($(az redis show --name contosoCache --resource-group contosoGroup --query [hostName,enableNonSslPort,port,sslPort] --output tsv))

# Retrieve the keys for an Azure Redis Cache instance
keys=($(az redis list-keys --name contosoCache --resource-group contosoGroup --query [primaryKey,secondaryKey] --output tsv))

# Display the retrieved hostname, keys, and ports
echo "Hostname:" ${redis[0]}
echo "Non SSL Port:" ${redis[2]}
echo "Non SSL Port Enabled:" ${redis[1]}
echo "SSL Port:" ${redis[3]}
echo "Primary Key:" ${keys[0]}
echo "Secondary Key:" ${keys[1]}
有关此脚本的详细信息,请参阅获取 Azure Redis 缓存的主机名、端口和密钥。 有关 Azure CLI 2.0 的详细信息,请参阅 Install Azure CLI 2.0(安装 Azure CLI 2.0)和 Get started with Azure CLI 2.0(Azure CLI 2.0 入门)。
使用 SSL 安全地连接到缓存
最新版本的 jedis 支持使用 SSL 连接到 Azure Redis 缓存。以下示例显示了如何使用 SSL 终结点 6380 连接到 Azure Redis 缓存。将 <name> 替换为缓存名称,将 <key> 替换为主密钥或辅助密钥,如前面的检索主机名和访问密钥部分中所述。

复制
boolean useSsl = true;
/* In this line, replace <name> with your cache name: */
JedisShardInfo shardInfo = new JedisShardInfo("<name>.redis.cache.chinacloudapi.cn", 6380, useSsl);
shardInfo.setPassword("<key>"); /* Use your access key. */
Note
为新的 Azure Redis 缓存实例禁用了非 SSL 端口。如果使用的是不支持 SSL 的不同客户端,请参阅如何启用非 SSL 端口。
在缓存中添加一些内容并检索此内容

复制
package com.mycompany.app;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

public class App
{
public static void main( String[] args )
{
boolean useSsl = true;
/* In this line, replace <name> with your cache name: */
JedisShardInfo shardInfo = new JedisShardInfo("<name>.redis.cache.chinacloudapi.cn", 6380, useSsl);
shardInfo.setPassword("<key>"); /* Use your access key. */
Jedis jedis = new Jedis(shardInfo);
jedis.set("foo", "bar");
String value = jedis.get("foo");
}
}

关于如何在 Azure 上创建 Redis 缓存以及操作界面截图,大家可以点击这里阅读。
...全文
141 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
李德胜1995 2017-08-24
  • 打赏
  • 举报
回复

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧