https://www.concretepage.com/spring-4/spring-data-redis-example
本页将走过春天的redis实例数据。弹簧数据提供的API与轻松的使用操作。Redis是一个开源的,内存中的数据结构存储,可以作为数据库,缓存和消息代理。Redis支持的数据结构,如字符串、哈希表、列表、集合等redis是NoSQL存储和使用键/值来存储数据。春天的数据提供不同的连接工厂把redis连接。连接工厂的例子jedisconnectionfactory,lettuceconnectionfactory等在我们的例子中我们将使用jedisconnectionfactory。不过是一个redis java客户端,使用方便,小尺寸。弹簧提供的数据执行操作redistemplate redis。redistemplate方法如opsforlist(),opsforset(),opsforhash()等返回listoperations,集合,hashoperations分别。大部分时间我们执行redis操作字符串数据类型。所以春天的数据提供了一个字符串集中扩展延伸redistemplate stringredistemplate。所以stringredistemplate所有方法的RedisTemplate执行redis操作基于字符串数据类型。在我们的例子中,我们将提供数据和Redis的配置使用弹簧javaconfig以及完整的示例XML配置。
1、pom.xml
2、Person.java
package com.concretepage.bean;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public Person() { }
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return id +" - " + name + " - " + age;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
final Person person = (Person) obj;
if (this == person) {
return true;
} else {
return (this.name.equals(person.name) && this.age == person.age);
}
}
@Override
public int hashCode() {
int hashno = 7;
hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
return hashno;
}
}
3、RedisConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.concretepage.bean.Person;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@ComponentScan("com.concretepage")
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(5);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
connectionFactory.setUsePool(true);
connectionFactory.setHostName("localhost");
connectionFactory.setPort(6379);
return connectionFactory;
}
@Bean
public RedisTemplate
RedisTemplate
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setEnableTransactionSupport(true);
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate() {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(redisConnectionFactory());
stringRedisTemplate.setEnableTransactionSupport(true);
return stringRedisTemplate;
}
}
4、UserDAO.java
package com.concretepage.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public class UserDAO {
private static final String KEY = "user";
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void addUserName(String uname) {
stringRedisTemplate.opsForValue().setIfAbsent(KEY, uname);
}
public void updateUserName(String uname) {
stringRedisTemplate.opsForValue().set(KEY, uname);
}
public String getUserName() {
return stringRedisTemplate.opsForValue().get(KEY);
}
public void deleteUser() {
stringRedisTemplate.delete(KEY);
}
}
5、FriendDAO
package com.concretepage.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.concretepage.bean.Person;
@Repository
@Transactional
public class FriendDAO {
private static final String KEY = "friends";
@Autowired
private RedisTemplate
public void addFriend(Person person) {
redisTemplate.opsForList().leftPush(KEY, person);
}
public long getNumberOfFriends() {
return redisTemplate.opsForList().size(KEY);
}
public Person getFriendAtIndex(Integer index) {
return redisTemplate.opsForList().index(KEY, index);
}
public void removeFriend(Person p) {
redisTemplate.opsForList().remove(KEY, 1, p);
}
}
6、FamilyDAO
package com.concretepage.dao;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.concretepage.bean.Person;
@Repository
@Transactional
public class FamilyDAO {
private static final String KEY = "myfamily";
@Resource(name="redisTemplate")
private SetOperations
public void addFamilyMembers(Person... persons) {
setOps.add(KEY, persons);
}
public Set
return setOps.members(KEY);
}
public long getNumberOfFamilyMembers() {
return setOps.size(KEY);
}
public long removeFamilyMembers(Person... persons) {
return setOps.remove(KEY, (Object[])persons);
}
}
7、EmployeeDAO
package com.concretepage.dao;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.concretepage.bean.Person;
@Repository
@Transactional
public class EmployeeDAO {
private static final String KEY = "employees";
@Resource(name="redisTemplate")
private HashOperations
public void addEmployee(Person person) {
hashOps.putIfAbsent(KEY, person.getId(), person);
}
public void updateEmployee(Person person) {
hashOps.put(KEY, person.getId(), person);
}
public Person getEmployee(Integer id) {
return hashOps.get(KEY, id);
}
public long getNumberOfEmployees() {
return hashOps.size(KEY);
}
public Map
return hashOps.entries(KEY);
}
public long deleteEmployees(Integer... ids) {
return hashOps.delete(KEY, (Object)ids);
}
}
8、main
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.bean.Person;
import com.concretepage.config.RedisConfig;
import com.concretepage.dao.EmployeeDAO;
import com.concretepage.dao.FamilyDAO;
import com.concretepage.dao.FriendDAO;
import com.concretepage.dao.UserDAO;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(RedisConfig.class);
context.refresh();
System.out.println("--Example of RedisTemplate for ListOperations--");
FriendDAO friendDAO = context.getBean(FriendDAO.class);
Person p1 = new Person(1, "Mahesh", 30);
friendDAO.addFriend(p1);
Person p2 = new Person(2, "Krishna", 35);
friendDAO.addFriend(p2);
System.out.println("Number of friends: " + friendDAO.getNumberOfFriends());
System.out.println(friendDAO.getFriendAtIndex(1));
friendDAO.removeFriend(p2);
System.out.println(friendDAO.getFriendAtIndex(1)); //It will return null, because value is deleted.
System.out.println("--Example of SetOperations--");
FamilyDAO familyDAO = context.getBean(FamilyDAO.class);
Person p11 = new Person(101, "Ram", 30);
Person p12 = new Person(102, "Lakshman", 25);
Person p13 = new Person(103, "Bharat", 35);
familyDAO.addFamilyMembers(p11, p12, p13);
System.out.println("Number of Family members: " + familyDAO.getNumberOfFamilyMembers());
System.out.println(familyDAO.getFamilyMembers());
System.out.println("No. of Removed Family Members: " + familyDAO.removeFamilyMembers(p11, p12));
System.out.println(familyDAO.getFamilyMembers());
System.out.println("--Example of HashOperations--");
EmployeeDAO empDAO = context.getBean(EmployeeDAO.class);
Person emp1 = new Person(11, "Ravan", 45);
Person emp2 = new Person(12, "Kumbhkarn", 35);
Person emp3 = new Person(13, "Vibhisan", 25);
empDAO.addEmployee(emp1);
empDAO.addEmployee(emp2);
empDAO.addEmployee(emp3);
System.out.println("No. of Employees: "+ empDAO.getNumberOfEmployees());
System.out.println(empDAO.getAllEmployees());
emp2.setAge(20);
empDAO.updateEmployee(emp2);
System.out.println(empDAO.getEmployee(12));
System.out.println("--Example of StringRedisTemplate--");
UserDAO userDAO = context.getBean(UserDAO.class);
userDAO.addUserName("sriram");
System.out.println(userDAO.getUserName());
userDAO.updateUserName("srikrishna");
System.out.println(userDAO.getUserName());
userDAO.deleteUser();
System.out.println(userDAO.getUserName()); //It will return null, because value is deleted.
}
}