依赖和配置都已经 OK,接下来就可以将 redisTemplate 注入到 java 代码里,实现对 Redis 的操作了:
package com.techlog.test.service;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Created by techlog on 16/8/15.
*/
@Service("testReids")
public class TestRedis {
@Resource
private RedisTemplate redisTemplate;
public void testSet() {
redisTemplate.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection redisConnection)
throws DataAccessException {
redisConnection.hSet(
"tempkey".getBytes(),
"hello".getBytes(),
"world".getBytes());
return true;
}
});
}
}
我们可以通过 junit 来调用他:
package com.techlog.test.service
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import javax.annotation.Resource
/**
* Created by techlog on 16/8/15.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
class TestRedisTest {
@Resource
private TestRedis testRedis;
@Test
public void testTestSet() throws Exception {
testRedis.testSet();
}
}
执行脚本,再通过 redis-client 查看,可以看到相应的数据已经写入到 Redis 中了: