JAVA后端《工具类》

1.分页工具类


@Data
@NoArgsConstructor
public class EasyPageInfo {
    //1.当前页码
    private Integer pageNum;
    //2.每页显示的条数
    private Integer pageSize;
    //3.数据库中总条数
    private Integer dbTotal;
    //4.根据pageSize和dbTotal和计算出来的总页数
    private Integer totalPages;
    //5.是否有上一页
    private boolean hasPrePage;
    //6.是否有下一页
    private boolean hasNextPage;
    //7.分页查询后的数据集合
    private List<?> dbList;
    //8.前端导航开始页码
    private Integer start;
    //9.前端导航结束页码
    private Integer end;
    //10.自定义导航页码总数,默认10
    private Integer navTotal;
    //11.前端导航的页码集合
    private List<Integer> numbers = new ArrayList<>();

    public EasyPageInfo (Integer pageNum, Integer pageSize, Integer dbTotal, List<?> dbList,Integer... navTotal){

        this.pageNum    = pageNum;
        this.pageSize   = pageSize;
        this.dbTotal    = dbTotal;
        this.totalPages = (dbTotal / pageSize) + (dbTotal % pageSize == 0 ? 0 : 1);
        this.hasPrePage = (pageNum > 1);
        this.hasNextPage= (pageNum < this.totalPages);
        this.dbList     = dbList;
        this.navTotal   = (navTotal.length > 0)?navTotal[0]:10;
        if (this.totalPages <= this.navTotal){
               this.start= 1;
               this.end  = this.totalPages;
        }else {
               this.start = this.pageNum - (this.navTotal%2==0?(this.navTotal/2-1):(this.navTotal/2));
               this.end   = this.pageNum + this.navTotal/2;
               if (this.start < 1){
                   this.start = 1;
                   this.end = this.navTotal;
               }else if (this.end > this.totalPages){
                   this.end =   this.totalPages;
                   this.start = this.totalPages-(this.navTotal-1);
               }
        }

        for (int i = this.start; i <= this.end; i++) {
            this.numbers.add(i);
        }

    }


}

2.Redis工具类

/**
 * Redis工具类
 */
@Component
public class RedisClient {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    // =============================common============================

    /**

     * 指定缓存失效时间

     * @param key 键

     * @param time 时间(秒)

     * @return

     */
    @SuppressWarnings("all")
    public boolean expire(String key, long time) {

        try {

            if (time > 0)
                return redisTemplate.expire(key, time, TimeUnit.SECONDS);
            else
                return false;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 根据key 获取过期时间

     * @param key 键 不能为null

     * @return 时间(秒) 返回0代表为永久有效

     */
    @SuppressWarnings("all")
    public long getExpire(String key) {

        return redisTemplate.getExpire(key, TimeUnit.SECONDS);

    }


    /**

     * 判断key是否存在

     * @param key 键

     * @return true 存在 false不存在

     */
    @SuppressWarnings("all")
    public boolean hasKey(String key) {

        try {

            return redisTemplate.hasKey(key);

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 删除缓存

     * @param key 可以传一个值 或多个

     */

    public void del(String... key) {

        if (key != null && key.length > 0) {

            if (key.length == 1) {

                redisTemplate.delete(key[0]);

            } else {

                redisTemplate.delete(Arrays.asList(key));

            }

        }

    }


    // ============================String=============================

    /**

     * 普通缓存获取

     * @param key 键

     * @return 值

     */

    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);

    }

    @SuppressWarnings("unchecked")
    public <T> T getBean(String key,Class<T> beanClass){
        return key == null ? null : (T)redisTemplate.opsForValue().get(key);
    }

    @SuppressWarnings("unchecked")
    public<T> List<T> getBeanList(String key,Class<T> tClass){
        return key == null ? null : (List<T>)redisTemplate.opsForValue().get(key);
    }
    @SuppressWarnings("unchecked")
    public<T> List<List<T>> getNestedBeanList(String key,Class<T> beanClass){
        return key == null ? null : (List<List<T>>)redisTemplate.opsForValue().get(key);
    }
    /**

     * 普通缓存放入

     * @param key 键

     * @param value 值

     * @return true成功 false失败

     */
    @SuppressWarnings("all")
    public boolean set(String key, Object value) {

        try {

            redisTemplate.opsForValue().set(key, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }


    }


    /**

     * 普通缓存放入并设置时间

     * @param key 键

     * @param value 值

     * @param time 时间大小---> 如果time小于等于0 将设置无限期

     * @param timeUnit: 时间单位

     * @return true成功 false 失败

     */
    @SuppressWarnings("all")
    public boolean set(String key, Object value, long time,TimeUnit timeUnit) {

        try {

            if (time > 0) {

                redisTemplate.opsForValue().set(key, value, time, timeUnit);

            } else {

                set(key, value);

            }

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 递增

     * @param key 键

     * @param delta 要增加几(大于0)

     * @return long

     */
    @SuppressWarnings("all")
    public long incr(String key, long delta) {

        if (delta < 0) {

            throw new RuntimeException("递增因子必须大于0");

        }

        return redisTemplate.opsForValue().increment(key, delta);

    }


    /**

     * 递减

     * @param key 键

     * @param delta 要减少几(小于0)

     * @return

     */
    @SuppressWarnings("all")
    public long decr(String key, long delta) {

        if (delta < 0) {

            throw new RuntimeException("递减因子必须大于0");

        }

        return redisTemplate.opsForValue().increment(key, -delta);

    }


    // ================================Hash=================================

    /**

     * HashGet

     * @param key 键 不能为null

     * @param item 项 不能为null

     * @return 值

     */

    public Object hget(String key, String item) {

        return redisTemplate.opsForHash().get(key, item);

    }


    /**

     * 获取hashKey对应的所有键值

     * @param key 键

     * @return 对应的多个键值

     */

    public Map<Object, Object> hmget(String key) {

        return redisTemplate.opsForHash().entries(key);

    }


    /**

     * HashSet

     * @param key 键

     * @param map 对应多个键值

     * @return true 成功 false 失败

     */

    public boolean hmset(String key, Map<String, Object> map) {

        try {

            redisTemplate.opsForHash().putAll(key, map);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * HashSet 并设置时间

     * @param key 键

     * @param map 对应多个键值

     * @param time 时间(秒)

     * @return true成功 false失败

     */

    public boolean hmset(String key, Map<String, Object> map, long time) {

        try {

            redisTemplate.opsForHash().putAll(key, map);

            if (time > 0) {

                expire(key, time);

            }

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 向一张hash表中放入数据,如果不存在将创建

     * @param key 键

     * @param item 项

     * @param value 值

     * @return true 成功 false失败

     */

    public boolean hset(String key, String item, Object value) {

        try {

            redisTemplate.opsForHash().put(key, item, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 向一张hash表中放入数据,如果不存在将创建

     * @param key 键

     * @param item 项

     * @param value 值

     * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间

     * @return true 成功 false失败

     */

    public boolean hset(String key, String item, Object value, long time) {

        try {

            redisTemplate.opsForHash().put(key, item, value);

            if (time > 0) {

                expire(key, time);

            }

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 删除hash表中的值

     * @param key 键 不能为null

     * @param item 项 可以使多个 不能为null

     */

    public void hdel(String key, Object... item) {

        redisTemplate.opsForHash().delete(key, item);

    }


    /**

     * 判断hash表中是否有该项的值

     * @param key 键 不能为null

     * @param item 项 不能为null

     * @return true 存在 false不存在

     */

    public boolean hHasKey(String key, String item) {

        return redisTemplate.opsForHash().hasKey(key, item);

    }


    /**

     * hash递增 如果不存在,就会创建一个 并把新增后的值返回

     * @param key 键

     * @param item 项

     * @param by 要增加几(大于0)

     * @return

     */

    public double hincr(String key, String item, double by) {

        return redisTemplate.opsForHash().increment(key, item, by);

    }


    /**

     * hash递减

     * @param key 键

     * @param item 项

     * @param by 要减少记(小于0)

     * @return

     */

    public double hdecr(String key, String item, double by) {

        return redisTemplate.opsForHash().increment(key, item, -by);

    }


    // ============================Set=============================

    /**

     * 根据key获取Set中的所有值

     * @param key 键

     * @return

     */

    public Set<Object> sGet(String key) {

        try {

            return redisTemplate.opsForSet().members(key);

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }


    /**

     * 根据value从一个set中查询,是否存在

     * @param key 键

     * @param value 值

     * @return true 存在 false不存在

     */
    @SuppressWarnings("all")
    public boolean sHasKey(String key, Object value) {

        try {

            return redisTemplate.opsForSet().isMember(key, value);

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 将数据放入set缓存

     * @param key 键

     * @param values 值 可以是多个

     * @return 成功个数

     */
    @SuppressWarnings("all")
    public long sSet(String key, Object... values) {

        try {

            return redisTemplate.opsForSet().add(key, values);

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }


    /**

     * 将set数据放入缓存

     * @param key 键

     * @param time 时间(秒)

     * @param values 值 可以是多个

     * @return 成功个数

     */
    @SuppressWarnings("all")
    public long sSetAndTime(String key, long time, Object... values) {

        try {

            Long count = redisTemplate.opsForSet().add(key, values);

            if (time > 0)

                expire(key, time);

            return count;

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }


    /**

     * 获取set缓存的长度

     * @param key 键

     * @return

     */
    @SuppressWarnings("all")
    public long sGetSetSize(String key) {

        try {

            return redisTemplate.opsForSet().size(key);

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }


    /**

     * 移除值为value的

     * @param key 键

     * @param values 值 可以是多个

     * @return 移除的个数

     */
    @SuppressWarnings("all")
    public long setRemove(String key, Object... values) {

        try {

            Long count = redisTemplate.opsForSet().remove(key, values);

            return count;

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }

    // ===============================list=================================


    /**

     * 获取list缓存的内容

     * @param key 键

     * @param start 开始

     * @param end 结束 0 到 -1代表所有值

     * @return List<Object>

     */

    public List<Object> lGet(String key, long start, long end) {

        try {

            return redisTemplate.opsForList().range(key, start, end);

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }


    /**

     * 获取list缓存的长度

     * @param key 键

     * @return

     */
    @SuppressWarnings("all")
    public long lGetListSize(String key) {

        try {

            return redisTemplate.opsForList().size(key);

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }


    /**

     * 通过索引 获取list中的值

     * @param key 键

     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推

     * @return Object

     */

    public Object lGetIndex(String key, long index) {

        try {

            return redisTemplate.opsForList().index(key, index);

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }


    /**

     * 将list放入缓存

     * @param key 键

     * @param value 值

     * @return boolean

     */

    public boolean lSet(String key, Object value) {

        try {

            redisTemplate.opsForList().rightPush(key, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 将list放入缓存

     * @param key 键

     * @param value 值

     * @param time 时间(秒)

     * @return boolean

     */

    public boolean lSet(String key, Object value, long time) {

        try {

            redisTemplate.opsForList().rightPush(key, value);

            if (time > 0)

                expire(key, time);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 将list放入缓存

     * @param key 键

     * @param value 值

     * @return boolean

     */

    public boolean lSet(String key, List<Object> value) {

        try {

            redisTemplate.opsForList().rightPushAll(key, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 将list放入缓存

     *

     * @param key 键

     * @param value 值

     * @param time 时间(秒)

     * @return boolean

     */

    public boolean lSet(String key, List<Object> value, long time) {

        try {

            redisTemplate.opsForList().rightPushAll(key, value);

            if (time > 0)

                expire(key, time);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 根据索引修改list中的某条数据

     * @param key 键

     * @param index 索引

     * @param value 值

     * @return boolean

     */

    public boolean lUpdateIndex(String key, long index, Object value) {

        try {

            redisTemplate.opsForList().set(key, index, value);

            return true;

        } catch (Exception e) {

            e.printStackTrace();

            return false;

        }

    }


    /**

     * 移除N个值为value

     * @param key 键

     * @param count 移除多少个

     * @param value 值

     * @return 移除的个数

     */
    @SuppressWarnings("all")
    public long lRemove(String key, long count, Object value) {

        try {

            Long remove = redisTemplate.opsForList().remove(key, count, value);

            return remove;

        } catch (Exception e) {

            e.printStackTrace();

            return 0;

        }

    }

}

3.IP地址工具类

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取IP方法
 * 
 * @author ruoyi
 */
public class IpUtils
{
    public static String getIpAddr(HttpServletRequest request)
    {
        if (request == null)
        {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    public static boolean internalIp(String ip)
    {
        byte[] addr = textToNumericFormatV4(ip);
        return internalIp(addr) || "127.0.0.1".equals(ip);
    }

    private static boolean internalIp(byte[] addr)
    {
        if (addr==null || addr.length < 2)
        {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        // 10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        // 172.16.x.x/12
        final byte SECTION_2 = (byte) 0xAC;
        final byte SECTION_3 = (byte) 0x10;
        final byte SECTION_4 = (byte) 0x1F;
        // 192.168.x.x/16
        final byte SECTION_5 = (byte) 0xC0;
        final byte SECTION_6 = (byte) 0xA8;
        switch (b0)
        {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4)
                {
                    return true;
                }
            case SECTION_5:
                switch (b1)
                {
                    case SECTION_6:
                        return true;
                }
            default:
                return false;
        }
    }

    /**
     * 将IPv4地址转换成字节
     * 
     * @param text IPv4地址
     * @return byte 字节
     */
    public static byte[] textToNumericFormatV4(String text)
    {
        if (text.length() == 0)
        {
            return null;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try
        {
            long l;
            int i;
            switch (elements.length)
            {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L))
                        return null;
                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L))
                        return null;
                    bytes[0] = (byte) (int) (l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L))
                        return null;
                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i)
                    {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L))
                            return null;
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L))
                        return null;
                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i)
                    {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L))
                            return null;
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    break;
                default:
                    return null;
            }
        }
        catch (NumberFormatException e)
        {
            return null;
        }
        return bytes;
    }

    public static String getHostIp()
    {
        try
        {
            return InetAddress.getLocalHost().getHostAddress();
        }
        catch (UnknownHostException e)
        {
        }
        return "127.0.0.1";
    }

    public static String getHostName()
    {
        try
        {
            return InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException e)
        {
        }
        return "未知";
    }
}

版权声明:本文为weixin_43766298原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。