在redis集群搭建完成的基础上:
1.配置application.properties:
#server.context-path=/redis
server.context-path=/redis
server.port=8001
spring.redis.pool.max-active=100
spring.redis.pool.max-wait=5
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=5
spring.redis.timeout=60000
spring.redis.cluster.max-redirects=1000
spring.redis.cluster.nodes=192.168.1.11:5001,192.168.1.11:5002,192.168.1.11:5003,192.168.1.11:5004,192.168.1.11:5005,192.168.1.11:5006
2.引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
3.创建RedisService:
package com.cc.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String,String> redisTemplate;
public void ste(String key,String value) {
ValueOperations<String,String> vops = redisTemplate.opsForValue();
vops.set(key, value);
}
public String get(String key) {
ValueOperations<String,String> vops = redisTemplate.opsForValue();
return vops.get(key);
}
public void putHash(String hashKey,String itemKey,String itemValue) {
HashOperations<String, Object, Object> hops = redisTemplate.opsForHash();
hops.put(hashKey, itemKey, itemValue);
}
public String getHash(String hashKey,String itemKey) {
HashOperations<String, Object, Object> hops = redisTemplate.opsForHash();
return (String) hops.get(hashKey, itemKey);
}
}
4.测试:
package com.cc.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.cc.springboot.service.RedisService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
private RedisService redisService;
@Test
public void test() throws Exception{
redisService.ste("51cto", "123456");
redisService.ste("bhx", "67890");
System.out.println(redisService.get("51cto"));
System.out.println(redisService.get("bhx"));
//redisService.putHash("user:0001", "name", "z3");
//redisService.putHash("user:0001", "age", "20");
//System.out.println(redisService.getHash("user:0001", "name"));
//System.out.println(redisService.getHash("user:0001", "age"));
}
}