1. 简介
springboot对常用的数据库支持外,对nosql 数据库也进行了封装自动化,为了方便其他应用程序快捷、方便的使用redis,而不用去管理连接,存储等,故把对redis逻辑操作如增、删、改、查放到tars(rpc框架)下,以达到上述目的。
2. Tars服务搭建
2.1在IDEA开发工具中打开新建工程
2.2点击下一步后,在对话框中填写如图中的内容
点击下一步直到结束
2.3配置pom.xml
2.3.1 添加tars相关配置
2.3.2 添加springboot相关配置
2.3.3 添加redis相关配置
2.4添加tars文件,路径要与pom.xml中的一样
RedisTest.tars文件内容
2.5添加属性配置文件application.properties
2.6 利用tars文件生成对应代码
执行上述命令会增加下图红色部分代码
2.7 增加impl目录并创建RedisTestServantImpl类,实现上图中的接口
3. Springboot整合Redis
添加下图红色标注的目录与文件
RedisConf主要是配置管理类,负责相关配置类的自动注入
package com.ancun.RedisTest.app.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
@EnableAutoConfiguration
@PropertySource(value={"classpath:application.properties"})
@ComponentScan("com.ancun.RedisTest.app.service")
public class RedisConfig {
/**
* 注入 RedisConnectionFactory
*/
@Autowired
RedisConnectionFactory redisConnectionFactory;
/**
* 实例化 RedisTemplate 对象
*
* @return
*/
@Bean
public RedisTemplate
RedisTemplate
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 设置数据存入 redis 的序列化方式
*
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(RedisTemplate
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setConnectionFactory(factory);
}
/**
* 实例化 HashOperations 对象,可以使用 Hash 类型操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations
return redisTemplate.opsForHash();
}
/**
* 实例化 ValueOperations 对象,可以使用 String 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations
return redisTemplate.opsForValue();
}
/**
* 实例化 ListOperations 对象,可以使用 List 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations
return redisTemplate.opsForList();
}
/**
* 实例化 SetOperations 对象,可以使用 Set 操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations
return redisTemplate.opsForSet();
}
/**
* 实例化 ZSetOperations 对象,可以使用 ZSet 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations
return redisTemplate.opsForZSet();
}
}
RedisModel主要是要存储的对象
package com.ancun.RedisTest.app.model;
import java.io.Serializable;
public class RedisModel implements Serializable {
private String redisKey;//redis中的key
private String name;//姓名
private String tel;//电话
private String address;//住址
public String getRedisKey() {
return redisKey;
}
public void setRedisKey(String redisKey) {
this.redisKey = redisKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Service目录时对象操作接口的实现
package com.ancun.RedisTest.app.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public abstract class IRedisService
@Autowired
protected RedisTemplate
@Resource
protected HashOperations
/**
* 存入redis中的key
*
* @return
*/
protected abstract String getRedisKey();
/**
* 添加
*
* @param key key
* @param doamin 对象
* @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
*/
public void put(String key, T doamin, long expire) {
hashOperations.put(getRedisKey(), key, doamin);
if (expire != -1) {
redisTemplate.expire(getRedisKey(), expire, TimeUnit.SECONDS);
}
}
/**
* 删除
*
* @param key 传入key的名称
*/
public void remove(String key) {
hashOperations.delete(getRedisKey(), key);
}
/**
* 查询
*
* @param key 查询的key
* @return
*/
public T get(String key) {
return hashOperations.get(getRedisKey(), key);
}
/**
* 获取当前redis库下所有对象
*
* @return
*/
public List
return hashOperations.values(getRedisKey());
}
/**
* 查询查询当前redis库下所有key
*
* @return
*/
public Set
return hashOperations.keys(getRedisKey());
}
/**
* 判断key是否存在redis中
*
* @param key 传入key的名称
* @return
*/
public boolean isKeyExists(String key) {
return hashOperations.hasKey(getRedisKey(), key);
}
/**
* 查询当前key下缓存数量
*
* @return
*/
public long count() {
return hashOperations.size(getRedisKey());
}
/**
* 清空redis
*/
public void empty() {
Set
set.stream().forEach(key -> hashOperations.delete(getRedisKey(), key));
}
}
RedisServiceImpl .java文件
package com.ancun.RedisTest.app.service;
import com.ancun.RedisTest.app.model.RedisModel;
import org.springframework.stereotype.Service;
/**
* Created by Administrator on 2017/3/1 16:00.
*/
@Service
public class RedisServiceImpl extends IRedisService
private static final String REDIS_KEY = "Tars.Redis.Test";
@Override
protected String getRedisKey() {
return this.REDIS_KEY;
}
}
4. Tars服务启动springboot+redis
添加下图红色标注的目录与文件
Tars目录主要是在springboot中利用上下文中注入要启动的class的实现,
SpringContext.java文件
package com.ancun.RedisTest.app.tars;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
public class SpringContext {
private static ApplicationContext applicationContext=null;
public static void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if (SpringContext.applicationContext == null) {
SpringContext.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static
return getApplicationContext().getBean(clazz);
}
public static
return getApplicationContext().getBean(name, clazz);
}
}
SpringDispatcher.java文件
package com.ancun.RedisTest.app.tars;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDispatcher {
private static final Logger log = LoggerFactory.getLogger(SpringDispatcher.class);
public static void init(String configLocation) {
log.info("开始加载ClassPathXmlApplicationContext<{}>", configLocation);
ApplicationContext application = new ClassPathXmlApplicationContext(configLocation);
//ApplicationContext app = SpringApplication.run(App.class, args);
log.info("Spring启动成功");
SpringContext.setApplicationContext(application);
}
public static void init(Class>... annotatedClasses){
log.info("开始加载AnnotationConfigApplicationContext<{}>", Arrays.toString(annotatedClasses));
ApplicationContext ctx = new AnnotationConfigApplicationContext(annotatedClasses);
log.info("Spring启动成功");
SpringContext.setApplicationContext(ctx);
}
}
Listener目录主要是配置需要注入的class及Bean
RedisTestConf.java
package com.ancun.RedisTest.app.listener;
import com.ancun.RedisTest.app.config.RedisConfig;}
AppStartListener.java文件
package com.ancun.RedisTest.app.listener;
import com.ancun.RedisTest.app.tars.SpringDispatcher;
import com.qq.tars.server.core.AppContextEvent;
import com.qq.tars.server.core.AppContextListener;
import com.qq.tars.server.core.AppServantEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AppStartListener implements AppContextListener {
private static final Logger log = LoggerFactory.getLogger(AppStartListener.class);
@Override
public void appContextStarted(AppContextEvent event) {
try{
log.info("Tars服务 RedisTest 开始启动......");
SpringDispatcher.init(RedisTestConf.class);
}catch(Exception e){
log.error("Tars服务RedisTest启动失败,",e.getMessage(), e);
return;
}
log.info("Tars服务 RedisTest 启动成功......");
}
@Override
public void appServantStarted(AppServantEvent event) {
}
public static void main(String[] args) {
System.getProperties().put("projectName", "springApp");
SpringDispatcher.init(RedisTestConf.class);
}
}
上述功能的实现这里不做详细介绍,后续会有详细的学习