redis 의 초기 사용(1)
7214 단어 springboot
오류 사례:ERR wrong number of arguments for'sadd'command 모든 key 값 을 조회 할 때 얻 은 배열 은 빈 jedis.sadd("fangchuantou"notice”,arr);// arr 는 모든 key 의 배열 을 두 고 있 습 니 다.
단계 1:application.yml 에 redis 정 보 를 추가 합 니 다.
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///ggt
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
redis:
host: 10.9.251.200
port: 8100
password: redis001
jedis:
pool:
max-active: 1024
max-idle: 100
min-idle: 10
pagehelper:
helper-dialect: mysql
params: count=countsql
reasonable: true
support-methods-arguments: true
단계 2:설정 파일 클래스 추가,서버 시작 시 JedisPool 대상 만 들 기
package com.qf.fayuan.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
@Value(value = ("${spring.redis.host}"))
private String host;
@Value(value = ("${spring.redis.port}"))
private int port;
@Value(value =("${spring.redis.password}") )
private String password;
@Bean
public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig){
JedisPool jedisPool = new JedisPool(jedisPoolConfig,host,port,5000,password);
return jedisPool;
}
@Bean
public JedisPoolConfig jedisPoolConfig(){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(1024);
jedisPoolConfig.setMaxIdle(100);
jedisPoolConfig.setMinIdle(10);
return jedisPoolConfig;
}
}
단계 3:도구 클래스 를 설정 합 니 다.캐 시 에 없 으 면 데 이 터 를 추가 합 니 다.
package com.qf.fayuan.utils;
import redis.clients.jedis.Jedis;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class RedisUtils {
public static void hSet(int key, Object object, Jedis jedis){
//
Class> aClass = object.getClass();
//
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field : declaredFields) {
String fieldName = field.getName();
try {
// get/set
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, aClass);
// get
Method readMethod = propertyDescriptor.getReadMethod();
if (readMethod != null) {
//
Object result = readMethod.invoke(object);
if (result != null) {
//
jedis.hset(key + "noticeinfo", fieldName, result.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
제4 부분:서비스 부분
/**
* id ,
* @param id id
* @return
*/
@Override
public ResultBean getNoticeInfo(int id) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
// ,
Map stringMap = jedis.hgetAll(id + "noticeinfo");
if (stringMap == null || stringMap.isEmpty()) {
// , ,
Boolean fangchuantou_notice = jedis.sismember("fangchuantou_notice", String.valueOf(id));
if (fangchuantou_notice) {
Notice notice = noticeMapper.getNoticeInfo(id);
if (notice != null) {
//
RedisUtils.hSet(id, notice, jedis);
// ,
jedis.expire(id + "noticeinfo", 1800);
return ResultBean.setOk(notice);
}
}
}else {
return ResultBean.setOk(stringMap);
}
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
if (jedis != null) {
jedis.close();
}
}
return ResultBean.setError(ErrorCodeInterface.XIUGAIMIMASHIBAI," ",null);
}
다섯 번 째 부분:관통 을 방지 하기 위해 서버 가 시 작 될 때 데이터 베 이 스 를 옮 겨 다 니 며 모든 key 값 을 편리 하 게 합 니 다.
package com.qf.fayuan.config;
import com.qf.fayuan.mapper.NoticeMapper;
import com.qf.fayuan.notice.pojo.Notice;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.annotation.PostConstruct;
import java.util.List;
@Configuration
public class GetAllRedisConfig {
@Autowired
private JedisPool jedisPool;
@Autowired
private NoticeMapper noticeMapper;
@PostConstruct
public void init(){
Jedis jedis = jedisPool.getResource();
List list = noticeMapper.getAllNoticeKey();
// String[] arr = list.toArray(new String[list.size()]);
String[] arr = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
arr[i] = list.get(i).toString();
}
jedis.sadd("fangchuantou_notice",arr);
jedis.close();
}
}
여섯 번 째 부분:사용자 가 다른 작업 을 수행 할 때(삭제 및 검사)관통 방지 목록 을 실시 간 으로 업데이트 해 야 합 니 다.
@Service
public class NoticeServiceImpl implements NoticeService {
@Autowired
private NoticeMapper noticeMapper;
@Autowired
private JedisPool jedisPool;
@Override
public void addNotice(Notice notice) {
noticeMapper.addNotice(notice);
// ,
Jedis jedis = jedisPool.getResource();
jedis.sadd("fangchuantou_notice",notice.getId()+"");
jedis.close();
}
위 에서 주의 하 는 것 은 데 이 터 를 추가 한 후 대상 의 id 를 가 져 오 는 방법 입 니 다.selectkey 를 sql 삽입 문 뒤에 두 어야 합 니 다.
insert into rw_notice(number, user_id, notice_type_id, court_id, case_num,show_area, about_mobile, about_identify_num, about_name, name_id, create_time, update_time, img,status, trade_no, pub_time, pub_days) values (#{number},#{user_id},#{notice_type_id},#{court_id},#{case_num},#{show_area},#{about_mobile},#{about_identify_num},#{about_name},#{name_id},#{create_time},#{update_time},#{img},#{status},#{trade_no},#{pub_time},#{pub_days})
select LAST_INSERT_ID() as value
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin Springboot -- 파트 14 사용 사례 REST로 전환하여 POST로 JSON으로 전환前回 前回 前回 記事 の は は で で で で で で を 使っ 使っ 使っ て て て て て リクエスト を を 受け取り 、 reqeustbody で 、 その リクエスト の ボディ ボディ を を 受け取り 、 関数 内部 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.