您的位置:首页 > 数据库 > Redis

如何用SpringData连接Redis简单测试

2013-01-09 19:41 477 查看
本帖最后由 bsspirit 于 2013-1-9 18:31 编辑

环境:

java1.6

gradle

spring-data-redis:1.0.1.RELEASE

redis 2.2.12 (Ubuntu)

=======================================

打开redis的远程访问:

vi /etc/redis/redis.conf

#注释

#bind 127.0.0.1

gradle.build

apply plugin: 'java'

apply plugin: 'eclipse'

sourceCompatibility = 1.5

version = '1.0'

jar {

manifest {

attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version

}

}

repositories {

mavenCentral()

}

dependencies {

compile "org.springframework:spring-core:3.1.1.RELEASE"

compile "org.springframework:spring-context:3.1.1.RELEASE"

compile "org.springframework:spring-context-support:3.1.1.RELEASE"

compile "org.springframework:spring-beans:3.1.1.RELEASE"

compile "org.springframework:spring-tx:3.1.1.RELEASE"

compile "org.springframework.data:spring-data-redis:1.0.1.RELEASE"

testCompile "junit:junit4.+"

}

复制代码

Redis在spring-data中注册

@Bean

public RedisConnectionFactory redisConnectionFactory() {

JedisConnectionFactory cf = new JedisConnectionFactory();

cf.setHostName("192.168.1.68");

cf.setPort(6379);

cf.afterPropertiesSet();

return cf;

}

复制代码

启动程序

public static void main(String[] args) throws Exception {

ApplicationConfig app = (ApplicationConfig) RedisMain.getContext().getBean("applicationConfig");

RedisConnectionFactory connectionFactory = app.redisConnectionFactory();

RedisTemplate<String, String> redis = new RedisTemplate<String, String>();

redis.setConnectionFactory(connectionFactory);

redis.setKeySerializer(ApplicationConfig.StringSerializer.INSTANCE);

redis.setValueSerializer(ApplicationConfig.StringSerializer.INSTANCE);

ValueOperations<String, String> ops = redis.opsForValue();

String key = "a1";

String val = "abcd" + new Random().nextInt();

System.out.printf("set {%s:%s}\n", key, val);

ops.setIfAbsent(key, val);

String val2 = ops.get(key);

System.out.printf("get %s ==> %s\n", key, val2);

}

复制代码

测试结果:

set {a1:abcd-1011059188}

get a1 ==> abcd-1011059188

复制代码
./redis-cli

get a1

"abcd-1011059188"

复制代码

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: