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
        
    

좋은 웹페이지 즐겨찾기